<!DOCTYPE html><html><head><meta charset="utf-8"><style>body {
  width: 45em;
  border: 1px solid #ddd;
  outline: 1300px solid #fff;
  margin: 16px auto;
}

body .markdown-body
{
  padding: 30px;
}

@font-face {
  font-family: fontawesome-mini;
  src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAzUABAAAAAAFNgAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABbAAAABwAAAAcZMzaOEdERUYAAAGIAAAAHQAAACAAOQAET1MvMgAAAagAAAA+AAAAYHqhde9jbWFwAAAB6AAAAFIAAAFa4azkLWN2dCAAAAI8AAAAKAAAACgFgwioZnBnbQAAAmQAAAGxAAACZVO0L6dnYXNwAAAEGAAAAAgAAAAIAAAAEGdseWYAAAQgAAAFDgAACMz7eroHaGVhZAAACTAAAAAwAAAANgWEOEloaGVhAAAJYAAAAB0AAAAkDGEGa2htdHgAAAmAAAAAEwAAADBEgAAQbG9jYQAACZQAAAAaAAAAGgsICJBtYXhwAAAJsAAAACAAAAAgASgBD25hbWUAAAnQAAACZwAABOD4no+3cG9zdAAADDgAAABsAAAAmF+yXM9wcmVwAAAMpAAAAC4AAAAusPIrFAAAAAEAAAAAyYlvMQAAAADLVHQgAAAAAM/u9uZ4nGNgZGBg4ANiCQYQYGJgBEJuIGYB8xgABMMAPgAAAHicY2Bm42OcwMDKwMLSw2LMwMDQBqGZihmiwHycoKCyqJjB4YPDh4NsDP+BfNb3DIuAFCOSEgUGRgAKDgt4AAB4nGNgYGBmgGAZBkYGEAgB8hjBfBYGCyDNxcDBwMTA9MHhQ9SHrA8H//9nYACyQyFs/sP86/kX8HtB9UIBIxsDXICRCUgwMaACRoZhDwA3fxKSAAAAAAHyAHABJQB/AIEAdAFGAOsBIwC/ALgAxACGAGYAugBNACcA/wCIeJxdUbtOW0EQ3Q0PA4HE2CA52hSzmZDGe6EFCcTVjWJkO4XlCGk3cpGLcQEfQIFEDdqvGaChpEibBiEXSHxCPiESM2uIojQ7O7NzzpkzS8qRqnfpa89T5ySQwt0GzTb9Tki1swD3pOvrjYy0gwdabGb0ynX7/gsGm9GUO2oA5T1vKQ8ZTTuBWrSn/tH8Cob7/B/zOxi0NNP01DoJ6SEE5ptxS4PvGc26yw/6gtXhYjAwpJim4i4/plL+tzTnasuwtZHRvIMzEfnJNEBTa20Emv7UIdXzcRRLkMumsTaYmLL+JBPBhcl0VVO1zPjawV2ys+hggyrNgQfYw1Z5DB4ODyYU0rckyiwNEfZiq8QIEZMcCjnl3Mn+pED5SBLGvElKO+OGtQbGkdfAoDZPs/88m01tbx3C+FkcwXe/GUs6+MiG2hgRYjtiKYAJREJGVfmGGs+9LAbkUvvPQJSA5fGPf50ItO7YRDyXtXUOMVYIen7b3PLLirtWuc6LQndvqmqo0inN+17OvscDnh4Lw0FjwZvP+/5Kgfo8LK40aA4EQ3o3ev+iteqIq7wXPrIn07+xWgAAAAABAAH//wAPeJyFlctvG1UUh+/12DPN1B7P3JnYjj2Ox4/MuDHxJH5N3UdaEUQLqBIkfQQioJWQ6AMEQkIqsPGCPwA1otuWSmTBhjtps2ADWbJg3EpIXbGouqSbCraJw7kzNo2dRN1cnXN1ZvT7zuuiMEI7ncizyA0URofRBJpCdbQuIFShYY+GZRrxMDVtih5TwQPHtXDFFSIKoWIbuREBjLH27Ny4MsbVx+uOJThavebgVrNRLAiYx06rXsvhxLgWx9xpfHdrs/ekc2Pl2cpPCVEITQpwbj8VQhfXSq2m+Wxqaq2D73Kne5e3NjHqQNj3CRYlJlgUl/jRNP+2Gs2pNYRQiOnmUaQDqm30KqKiTTWPWjboxnTWpvgxjXo0KrtZXAHt7hwIz0YVcj88JnKlJKi3NPAwLyDwZudSmJSMMJFDYaOkaol6XtESx3Gt1VTytdZJ3DCLeaVhVnCBH1fycHTxFXwPX+l2e3d6H/TufGGmMTLTnbSJUdo00zuBswMO/nl3YLeL/wnu9/limCuD3vC54h5NBVz6Li414AI8Vx3iiosKcQXUbrvhFFiYb++HN4DaF4XzFW0fIN4XDWJ3a3XQoq9V8WiyRmdsatV9xUcHims1JloH0YUa090G3Tro3mC6c01f+YwCPquINr1PTaCP6rVTOOmf0GE2dBc7zWIhji3/5MchSuBHgDbU99RMWt3YUNMZMJmx92YP6NsHx/5/M1yvInpnkIOM3Z8fA3JQ2lW1RFC1KaBPDFXNAHYYvGy73aYZZZ3HifbeuiVZCpwA3oQBs0wGPYJbJfg60xrKEbKiNtTe1adwrpBRwlAuQ3q3VRaX0QmQ9a49BTSCuF1MLfQ6+tinOubRBZuWPNoMevGMT+V41KitO1is3D/tpMcq1JHZqDHGs8DoYGDkxJgKjHROeTCmhZvzPm9pod+ltKm4PN7Dyvvldlpsg8D+4AUJZ3F/JBstZz7cbFRxsaAGV6yX/dkcycWf8eS3QlQea+YLjdm3yrOnrhFpUyKVvFE4lpv4bO3Svx/6F/4xmiDu/RT5iI++lko18mY1oX+5UGKR6kmVjM/Zb76yfHtxy+h/SyQ0lLdpdKy/lWB6szatetQJ8nZ80A2Qt6ift6gJeavU3BO4gtxs/KCtNPVibCtYCWY3SIlSBPKXZALXiIR9oZeJ1AuMyxLpHIy/yO7vSiSE+kZvk0ihJ30HgHfzZtEMmvV58x6dtqns0XTAW7Vdm4HJ04OCp/crOO7rd9SGxQAE/mVA9xRN+kVSMRFF6S9JFGUtthkjBA5tFCWc2l4V43Ex9GmUP3SI37Jjmir9KqlaDJ4S4JB3vuM/jzyH1+8MuoZ+QGzfnvPoJb96cZlWjMcKLfgDwB7E634JTY+asjsPzS5CiVnEWY+KsrsIN5rn3mAPjqmQBxGjcGKB9f9ZxY3mYC2L85CJ2FXIxKKyHk+dg0FHbuEc7D5NzWUX32WxFcWNGRAbvwSx0RmIXVDuYySafluQBmzA/ssqJAMLnli+WIC90Gw4lm85wcp0qjArEDPJJV/sSx4P9ungTpgMw5gVC1XO4uULq0s3v1rqLi0vX/z65vlH50f8T/RHmSPTk5xxWBWOluMT6WiOy+tdvWxlV/XQb3o3c6Ssr+r6I708GsX9/nzp1tKFh0s3v7m4vAy/Hnb/KMOvc1wump6Il48K6mGDy02X9Yd65pa+nQIjk76lWxCkG8NBCP0HQS9IpAAAeJxjYGRgYGBhcCrq214Qz2/zlUGenQEEzr/77oug/zewFbB+AHI5GJhAogBwKQ0qeJxjYGRgYH3/P46BgZ0BBNgKGBgZUAEPAE/7At0AAAB4nGNngAB2IGYjhBsYBAAIYADVAAAAAAAAAAAAAFwAyAEeAaACCgKmAx4DggRmAAAAAQAAAAwAagAEAAAAAAACAAEAAgAWAAABAAChAAAAAHiclZI7bxQxFIWPd/JkUYQChEhIyAVKgdBMskm1QkKrRETpQiLRUczueB/K7HhlOxttg8LvoKPgP9DxFxANDR0tHRWi4NjrPIBEgh1p/dm+vufcawNYFWsQmP6e4jSyQB2fI9cwj++RE9wTjyPP4LYoI89iWbyLPIe6+Bh5Hs9rryMv4GbtW+RF3EhuRa7jbrIbeQkPkjdUETOLnL0Kip4FVvAhco1RXyMnSPEz8gzWxE7kWTwUp5HnsCLeR57HW/El8gJWa58iL+JO7UfkOh4l9yMv4UnyEtvQGGECgwF66MNBooF1bGCL1ELB/TYU+ZBRlvsKQ44Se6jQ4a7hef+fh72Crv25kp+8lNWGmeKoOI5jJLb1aGIGvb6TjfWNLdkqdFvJw4l1amjlXtXRZqRN7lSRylZZyhBqpVFWmTEXgWfUrpi/hZOQXdOd4rKuXOtEWT3k5IArPRzTUU5tHKjecZkTpnVbNOnt6jzN8240GD4xtikvZW56043rPMg/dS+dlOceXoR+WPbJ55Dsekq1lJpnypsMUsYOdCW30o103Ytu/lvh+5RWFLfBjm9/N8hJntPhvx92rnoE/kyHdGasGy754kw36vsVf/lFeBi+0COu+cfgQr42G3CRpeLoZ53gmfe3X6rcKt5oVxnptHR9JS8ehVUd5wvvahN2uqxOOpMXapibI5k7Zwbt4xBSaTfoKBufhAnO/uqNcfK8OTs0OQ6l7JIqFjDhYj5WcjevCnI/1DDiI8j4ndWb/5YzDZWh79yomWXeXj7Nnw70/2TIeFPTrlSh89k1ObOSRVZWZfgF0r/zJQB4nG2JUQuCQBCEd07TTg36fb2IyBaLd3vWaUh/vmSJnvpgmG8YcmS8X3Shf3R7QA4OBUocUKHGER5NNbOOEvwc1txnuWkTRb/aPjimJ5vXabI+3VfOiyS15UWvyezM2xiGOPyuMohOH8O8JiO4Af+FsAGNAEuwCFBYsQEBjlmxRgYrWCGwEFlLsBRSWCGwgFkdsAYrXFhZsBQrAAA=) format('woff');
}

@font-face {
  font-family: octicons-anchor;
  src: url(data:font/woff;charset=utf-8;base64,d09GRgABAAAAAAYcAA0AAAAACjQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABGRlRNAAABMAAAABwAAAAca8vGTk9TLzIAAAFMAAAARAAAAFZG1VHVY21hcAAAAZAAAAA+AAABQgAP9AdjdnQgAAAB0AAAAAQAAAAEACICiGdhc3AAAAHUAAAACAAAAAj//wADZ2x5ZgAAAdwAAADRAAABEKyikaNoZWFkAAACsAAAAC0AAAA2AtXoA2hoZWEAAALgAAAAHAAAACQHngNFaG10eAAAAvwAAAAQAAAAEAwAACJsb2NhAAADDAAAAAoAAAAKALIAVG1heHAAAAMYAAAAHwAAACABEAB2bmFtZQAAAzgAAALBAAAFu3I9x/Nwb3N0AAAF/AAAAB0AAAAvaoFvbwAAAAEAAAAAzBdyYwAAAADP2IQvAAAAAM/bz7t4nGNgZGFgnMDAysDB1Ml0hoGBoR9CM75mMGLkYGBgYmBlZsAKAtJcUxgcPsR8iGF2+O/AEMPsznAYKMwIkgMA5REMOXicY2BgYGaAYBkGRgYQsAHyGMF8FgYFIM0ChED+h5j//yEk/3KoSgZGNgYYk4GRCUgwMaACRoZhDwCs7QgGAAAAIgKIAAAAAf//AAJ4nHWMMQrCQBBF/0zWrCCIKUQsTDCL2EXMohYGSSmorScInsRGL2DOYJe0Ntp7BK+gJ1BxF1stZvjz/v8DRghQzEc4kIgKwiAppcA9LtzKLSkdNhKFY3HF4lK69ExKslx7Xa+vPRVS43G98vG1DnkDMIBUgFN0MDXflU8tbaZOUkXUH0+U27RoRpOIyCKjbMCVejwypzJJG4jIwb43rfl6wbwanocrJm9XFYfskuVC5K/TPyczNU7b84CXcbxks1Un6H6tLH9vf2LRnn8Ax7A5WQAAAHicY2BkYGAA4teL1+yI57f5ysDNwgAC529f0kOmWRiYVgEpDgYmEA8AUzEKsQAAAHicY2BkYGB2+O/AEMPCAAJAkpEBFbAAADgKAe0EAAAiAAAAAAQAAAAEAAAAAAAAKgAqACoAiAAAeJxjYGRgYGBhsGFgYgABEMkFhAwM/xn0QAIAD6YBhwB4nI1Ty07cMBS9QwKlQapQW3VXySvEqDCZGbGaHULiIQ1FKgjWMxknMfLEke2A+IJu+wntrt/QbVf9gG75jK577Lg8K1qQPCfnnnt8fX1NRC/pmjrk/zprC+8D7tBy9DHgBXoWfQ44Av8t4Bj4Z8CLtBL9CniJluPXASf0Lm4CXqFX8Q84dOLnMB17N4c7tBo1AS/Qi+hTwBH4rwHHwN8DXqQ30XXAS7QaLwSc0Gn8NuAVWou/gFmnjLrEaEh9GmDdDGgL3B4JsrRPDU2hTOiMSuJUIdKQQayiAth69r6akSSFqIJuA19TrzCIaY8sIoxyrNIrL//pw7A2iMygkX5vDj+G+kuoLdX4GlGK/8Lnlz6/h9MpmoO9rafrz7ILXEHHaAx95s9lsI7AHNMBWEZHULnfAXwG9/ZqdzLI08iuwRloXE8kfhXYAvE23+23DU3t626rbs8/8adv+9DWknsHp3E17oCf+Z48rvEQNZ78paYM38qfk3v/u3l3u3GXN2Dmvmvpf1Srwk3pB/VSsp512bA/GG5i2WJ7wu430yQ5K3nFGiOqgtmSB5pJVSizwaacmUZzZhXLlZTq8qGGFY2YcSkqbth6aW1tRmlaCFs2016m5qn36SbJrqosG4uMV4aP2PHBmB3tjtmgN2izkGQyLWprekbIntJFing32a5rKWCN/SdSoga45EJykyQ7asZvHQ8PTm6cslIpwyeyjbVltNikc2HTR7YKh9LBl9DADC0U/jLcBZDKrMhUBfQBvXRzLtFtjU9eNHKin0x5InTqb8lNpfKv1s1xHzTXRqgKzek/mb7nB8RZTCDhGEX3kK/8Q75AmUM/eLkfA+0Hi908Kx4eNsMgudg5GLdRD7a84npi+YxNr5i5KIbW5izXas7cHXIMAau1OueZhfj+cOcP3P8MNIWLyYOBuxL6DRylJ4cAAAB4nGNgYoAALjDJyIAOWMCiTIxMLDmZedkABtIBygAAAA==) format('woff');
}

.markdown-body {
  font-family: sans-serif;
  -ms-text-size-adjust: 100%;
  -webkit-text-size-adjust: 100%;
  color: #333333;
  overflow: hidden;
  font-family: "Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif;
  font-size: 16px;
  line-height: 1.6;
  word-wrap: break-word;
}

.markdown-body a {
  background: transparent;
}

.markdown-body a:active,
.markdown-body a:hover {
  outline: 0;
}

.markdown-body b,
.markdown-body strong {
  font-weight: bold;
}

.markdown-body mark {
  background: #ff0;
  color: #000;
  font-style: italic;
  font-weight: bold;
}

.markdown-body sub,
.markdown-body sup {
  font-size: 75%;
  line-height: 0;
  position: relative;
  vertical-align: baseline;
}
.markdown-body sup {
  top: -0.5em;
}
.markdown-body sub {
  bottom: -0.25em;
}

.markdown-body h1 {
  font-size: 2em;
  margin: 0.67em 0;
}

.markdown-body img {
  border: 0;
}

.markdown-body hr {
  -moz-box-sizing: content-box;
  box-sizing: content-box;
  height: 0;
}

.markdown-body pre {
  overflow: auto;
}

.markdown-body code,
.markdown-body kbd,
.markdown-body pre,
.markdown-body samp {
  font-family: monospace, monospace;
  font-size: 1em;
}

.markdown-body input {
  color: inherit;
  font: inherit;
  margin: 0;
}

.markdown-body html input[disabled] {
  cursor: default;
}

.markdown-body input {
  line-height: normal;
}

.markdown-body input[type="checkbox"] {
  box-sizing: border-box;
  padding: 0;
}

.markdown-body table {
  border-collapse: collapse;
  border-spacing: 0;
}

.markdown-body td,
.markdown-body th {
  padding: 0;
}

.markdown-body .codehilitetable {
  border: 0;
  border-spacing: 0;
}

.markdown-body .codehilitetable tr {
  border: 0;
}

.markdown-body .codehilitetable pre,
.markdown-body .codehilitetable div.codehilite {
  margin: 0;
}

.markdown-body .linenos,
.markdown-body .code,
.markdown-body .codehilitetable td {
  border: 0;
  padding: 0;
}

.markdown-body td:not(.linenos) .linenodiv {
  padding: 0 !important;
}

.markdown-body .code {
  width: 100%;
}

.markdown-body .linenos div pre,
.markdown-body .linenodiv pre,
.markdown-body .linenodiv {
  border: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  -webkit-border-top-left-radius: 3px;
  -webkit-border-bottom-left-radius: 3px;
  -moz-border-radius-topleft: 3px;
  -moz-border-radius-bottomleft: 3px;
  border-top-left-radius: 3px;
  border-bottom-left-radius: 3px;
}

.markdown-body .code div pre,
.markdown-body .code div {
  border: 0;
  -webkit-border-radius: 0;
  -moz-border-radius: 0;
  border-radius: 0;
  -webkit-border-top-right-radius: 3px;
  -webkit-border-bottom-right-radius: 3px;
  -moz-border-radius-topright: 3px;
  -moz-border-radius-bottomright: 3px;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}

.markdown-body * {
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.markdown-body input {
  font: 13px Helvetica, arial, freesans, clean, sans-serif, "Segoe UI Emoji", "Segoe UI Symbol";
  line-height: 1.4;
}

.markdown-body a {
  color: #4183c4;
  text-decoration: none;
}

.markdown-body a:hover,
.markdown-body a:focus,
.markdown-body a:active {
  text-decoration: underline;
}

.markdown-body hr {
  height: 0;
  margin: 15px 0;
  overflow: hidden;
  background: transparent;
  border: 0;
  border-bottom: 1px solid #ddd;
}

.markdown-body hr:before,
.markdown-body hr:after {
  display: table;
  content: " ";
}

.markdown-body hr:after {
  clear: both;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 15px;
  margin-bottom: 15px;
  line-height: 1.1;
}

.markdown-body h1 {
  font-size: 30px;
}

.markdown-body h2 {
  font-size: 21px;
}

.markdown-body h3 {
  font-size: 16px;
}

.markdown-body h4 {
  font-size: 14px;
}

.markdown-body h5 {
  font-size: 12px;
}

.markdown-body h6 {
  font-size: 11px;
}

.markdown-body blockquote {
  margin: 0;
}

.markdown-body ul,
.markdown-body ol {
  padding: 0;
  margin-top: 0;
  margin-bottom: 0;
}

.markdown-body ol ol,
.markdown-body ul ol {
  list-style-type: lower-roman;
}

.markdown-body ul ul ol,
.markdown-body ul ol ol,
.markdown-body ol ul ol,
.markdown-body ol ol ol {
  list-style-type: lower-alpha;
}

.markdown-body dd {
  margin-left: 0;
}

.markdown-body code,
.markdown-body pre,
.markdown-body samp {
  font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
  font-size: 12px;
}

.markdown-body pre {
  margin-top: 0;
  margin-bottom: 0;
}

.markdown-body kbd {
  background-color: #e7e7e7;
  background-image: -moz-linear-gradient(#fefefe, #e7e7e7);
  background-image: -webkit-linear-gradient(#fefefe, #e7e7e7);
  background-image: linear-gradient(#fefefe, #e7e7e7);
  background-repeat: repeat-x;
  border-radius: 2px;
  border: 1px solid #cfcfcf;
  color: #000;
  padding: 3px 5px;
  line-height: 10px;
  font: 11px Consolas, "Liberation Mono", Menlo, Courier, monospace;
  display: inline-block;
}

.markdown-body>*:first-child {
  margin-top: 0 !important;
}

.markdown-body>*:last-child {
  margin-bottom: 0 !important;
}

.markdown-body .headeranchor-link {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  display: block;
  padding-right: 6px;
  padding-left: 30px;
  margin-left: -30px;
}

.markdown-body .headeranchor-link:focus {
  outline: none;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  position: relative;
  margin-top: 1em;
  margin-bottom: 16px;
  font-weight: bold;
  line-height: 1.4;
}

.markdown-body h1 .headeranchor,
.markdown-body h2 .headeranchor,
.markdown-body h3 .headeranchor,
.markdown-body h4 .headeranchor,
.markdown-body h5 .headeranchor,
.markdown-body h6 .headeranchor {
  display: none;
  color: #000;
  vertical-align: middle;
}

.markdown-body h1:hover .headeranchor-link,
.markdown-body h2:hover .headeranchor-link,
.markdown-body h3:hover .headeranchor-link,
.markdown-body h4:hover .headeranchor-link,
.markdown-body h5:hover .headeranchor-link,
.markdown-body h6:hover .headeranchor-link {
  height: 1em;
  padding-left: 8px;
  margin-left: -30px;
  line-height: 1;
  text-decoration: none;
}

.markdown-body h1:hover .headeranchor-link .headeranchor,
.markdown-body h2:hover .headeranchor-link .headeranchor,
.markdown-body h3:hover .headeranchor-link .headeranchor,
.markdown-body h4:hover .headeranchor-link .headeranchor,
.markdown-body h5:hover .headeranchor-link .headeranchor,
.markdown-body h6:hover .headeranchor-link .headeranchor {
  display: inline-block;
}

.markdown-body h1 {
  padding-bottom: 0.3em;
  font-size: 2.25em;
  line-height: 1.2;
  border-bottom: 1px solid #eee;
}

.markdown-body h2 {
  padding-bottom: 0.3em;
  font-size: 1.75em;
  line-height: 1.225;
  border-bottom: 1px solid #eee;
}

.markdown-body h3 {
  font-size: 1.5em;
  line-height: 1.43;
}

.markdown-body h4 {
  font-size: 1.25em;
}

.markdown-body h5 {
  font-size: 1em;
}

.markdown-body h6 {
  font-size: 1em;
  color: #777;
}

.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body .admonition {
  margin-top: 0;
  margin-bottom: 16px;
}

.markdown-body hr {
  height: 4px;
  padding: 0;
  margin: 16px 0;
  background-color: #e7e7e7;
  border: 0 none;
}

.markdown-body ul,
.markdown-body ol {
  padding-left: 2em;
}

.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ol,
.markdown-body ol ul {
  margin-top: 0;
  margin-bottom: 0;
}

.markdown-body li>p {
  margin-top: 16px;
}

.markdown-body dl {
  padding: 0;
}

.markdown-body dl dt {
  padding: 0;
  margin-top: 16px;
  font-size: 1em;
  font-style: italic;
  font-weight: bold;
}

.markdown-body dl dd {
  padding: 0 16px;
  margin-bottom: 16px;
}

.markdown-body blockquote {
  padding: 0 15px;
  color: #777;
  border-left: 4px solid #ddd;
}

.markdown-body blockquote>:first-child {
  margin-top: 0;
}

.markdown-body blockquote>:last-child {
  margin-bottom: 0;
}

.markdown-body table {
  display: block;
  width: 100%;
  overflow: auto;
  word-break: normal;
  word-break: keep-all;
}

.markdown-body table th {
  font-weight: bold;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 13px;
  border: 1px solid #ddd;
}

.markdown-body table tr {
  background-color: #fff;
  border-top: 1px solid #ccc;
}

.markdown-body table tr:nth-child(2n) {
  background-color: #f8f8f8;
}

.markdown-body img {
  max-width: 100%;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.markdown-body code,
.markdown-body samp {
  padding: 0;
  padding-top: 0.2em;
  padding-bottom: 0.2em;
  margin: 0;
  font-size: 85%;
  background-color: rgba(0,0,0,0.04);
  border-radius: 3px;
}

.markdown-body code:before,
.markdown-body code:after {
  letter-spacing: -0.2em;
  content: "\00a0";
}

.markdown-body pre>code {
  padding: 0;
  margin: 0;
  font-size: 100%;
  word-break: normal;
  white-space: pre;
  background: transparent;
  border: 0;
}

.markdown-body .codehilite {
  margin-bottom: 16px;
}

.markdown-body .codehilite pre,
.markdown-body pre {
  padding: 16px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  background-color: #f7f7f7;
  border-radius: 3px;
}

.markdown-body .codehilite pre {
  margin-bottom: 0;
  word-break: normal;
}

.markdown-body pre {
  word-wrap: normal;
}

.markdown-body pre code {
  display: inline;
  max-width: initial;
  padding: 0;
  margin: 0;
  overflow: initial;
  line-height: inherit;
  word-wrap: normal;
  background-color: transparent;
  border: 0;
}

.markdown-body pre code:before,
.markdown-body pre code:after {
  content: normal;
}

/* Admonition */
.markdown-body .admonition {
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  position: relative;
  border-radius: 3px;
  border: 1px solid #e0e0e0;
  border-left: 6px solid #333;
  padding: 10px 10px 10px 30px;
}

.markdown-body .admonition table {
  color: #333;
}

.markdown-body .admonition p {
  padding: 0;
}

.markdown-body .admonition-title {
  font-weight: bold;
  margin: 0;
}

.markdown-body .admonition>.admonition-title {
  color: #333;
}

.markdown-body .attention>.admonition-title {
  color: #a6d796;
}

.markdown-body .caution>.admonition-title {
  color: #d7a796;
}

.markdown-body .hint>.admonition-title {
  color: #96c6d7;
}

.markdown-body .danger>.admonition-title {
  color: #c25f77;
}

.markdown-body .question>.admonition-title {
  color: #96a6d7;
}

.markdown-body .note>.admonition-title {
  color: #d7c896;
}

.markdown-body .admonition:before,
.markdown-body .attention:before,
.markdown-body .caution:before,
.markdown-body .hint:before,
.markdown-body .danger:before,
.markdown-body .question:before,
.markdown-body .note:before {
  font: normal normal 16px fontawesome-mini;
  -moz-osx-font-smoothing: grayscale;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  line-height: 1.5;
  color: #333;
  position: absolute;
  left: 0;
  top: 0;
  padding-top: 10px;
  padding-left: 10px;
}

.markdown-body .admonition:before {
  content: "\f056\00a0";
  color: 333;
}

.markdown-body .attention:before {
  content: "\f058\00a0";
  color: #a6d796;
}

.markdown-body .caution:before {
  content: "\f06a\00a0";
  color: #d7a796;
}

.markdown-body .hint:before {
  content: "\f05a\00a0";
  color: #96c6d7;
}

.markdown-body .danger:before {
  content: "\f057\00a0";
  color: #c25f77;
}

.markdown-body .question:before {
  content: "\f059\00a0";
  color: #96a6d7;
}

.markdown-body .note:before {
  content: "\f040\00a0";
  color: #d7c896;
}

.markdown-body .admonition::after {
  content: normal;
}

.markdown-body .attention {
  border-left: 6px solid #a6d796;
}

.markdown-body .caution {
  border-left: 6px solid #d7a796;
}

.markdown-body .hint {
  border-left: 6px solid #96c6d7;
}

.markdown-body .danger {
  border-left: 6px solid #c25f77;
}

.markdown-body .question {
  border-left: 6px solid #96a6d7;
}

.markdown-body .note {
  border-left: 6px solid #d7c896;
}

.markdown-body .admonition>*:first-child {
  margin-top: 0 !important;
}

.markdown-body .admonition>*:last-child {
  margin-bottom: 0 !important;
}

/* progress bar*/
.markdown-body .progress {
  display: block;
  width: 300px;
  margin: 10px 0;
  height: 24px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #ededed;
  position: relative;
  box-shadow: inset -1px 1px 3px rgba(0, 0, 0, .1);
}

.markdown-body .progress-label {
  position: absolute;
  text-align: center;
  font-weight: bold;
  width: 100%; margin: 0;
  line-height: 24px;
  color: #333;
  text-shadow: 1px 1px 0 #fefefe, -1px -1px 0 #fefefe, -1px 1px 0 #fefefe, 1px -1px 0 #fefefe, 0 1px 0 #fefefe, 0 -1px 0 #fefefe, 1px 0 0 #fefefe, -1px 0 0 #fefefe, 1px 1px 2px #000;
  -webkit-font-smoothing: antialiased !important;
  white-space: nowrap;
  overflow: hidden;
}

.markdown-body .progress-bar {
  height: 24px;
  float: left;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  background-color: #96c6d7;
  box-shadow: inset 0 1px 0 rgba(255, 255, 255, .5), inset 0 -1px 0 rgba(0, 0, 0, .1);
  background-size: 30px 30px;
  background-image: -webkit-linear-gradient(
    135deg, rgba(255, 255, 255, .4) 27%,
    transparent 27%,
    transparent 52%, rgba(255, 255, 255, .4) 52%,
    rgba(255, 255, 255, .4) 77%,
    transparent 77%, transparent
  );
  background-image: -moz-linear-gradient(
    135deg,
    rgba(255, 255, 255, .4) 27%, transparent 27%,
    transparent 52%, rgba(255, 255, 255, .4) 52%,
    rgba(255, 255, 255, .4) 77%, transparent 77%,
    transparent
  );
  background-image: -ms-linear-gradient(
    135deg,
    rgba(255, 255, 255, .4) 27%, transparent 27%,
    transparent 52%, rgba(255, 255, 255, .4) 52%,
    rgba(255, 255, 255, .4) 77%, transparent 77%,
    transparent
  );
  background-image: -o-linear-gradient(
    135deg,
    rgba(255, 255, 255, .4) 27%, transparent 27%,
    transparent 52%, rgba(255, 255, 255, .4) 52%,
    rgba(255, 255, 255, .4) 77%, transparent 77%,
    transparent
  );
  background-image: linear-gradient(
    135deg,
    rgba(255, 255, 255, .4) 27%, transparent 27%,
    transparent 52%, rgba(255, 255, 255, .4) 52%,
    rgba(255, 255, 255, .4) 77%, transparent 77%,
    transparent
  );
}

.markdown-body .progress-100plus .progress-bar {
  background-color: #a6d796;
}

.markdown-body .progress-80plus .progress-bar {
  background-color: #c6d796;
}

.markdown-body .progress-60plus .progress-bar {
  background-color: #d7c896;
}

.markdown-body .progress-40plus .progress-bar {
  background-color: #d7a796;
}

.markdown-body .progress-20plus .progress-bar {
  background-color: #d796a6;
}

.markdown-body .progress-0plus .progress-bar {
  background-color: #c25f77;
}

.markdown-body .candystripe-animate .progress-bar{
  -webkit-animation: animate-stripes 3s linear infinite;
  -moz-animation: animate-stripes 3s linear infinite;
  animation: animate-stripes 3s linear infinite;
}

@-webkit-keyframes animate-stripes {
  0% {
    background-position: 0 0;
  }

  100% {
    background-position: 60px 0;
  }
}

@-moz-keyframes animate-stripes {
  0% {
    background-position: 0 0;
  }

  100% {
    background-position: 60px 0;
  }
}

@keyframes animate-stripes {
  0% {
    background-position: 0 0;
  }

  100% {
    background-position: 60px 0;
  }
}

.markdown-body .gloss .progress-bar {
  box-shadow:
    inset 0 4px 12px rgba(255, 255, 255, .7),
    inset 0 -12px 0 rgba(0, 0, 0, .05);
}

/* Multimarkdown Critic Blocks */
.markdown-body .critic_mark {
  background: #ff0;
}

.markdown-body .critic_delete {
  color: #c82829;
  text-decoration: line-through;
}

.markdown-body .critic_insert {
  color: #718c00 ;
  text-decoration: underline;
}

.markdown-body .critic_comment {
  color: #8e908c;
  font-style: italic;
}

.markdown-body .headeranchor {
  font: normal normal 16px octicons-anchor;
  line-height: 1;
  display: inline-block;
  text-decoration: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.headeranchor:before {
  content: '\f05c';
}

.markdown-body .task-list-item {
  list-style-type: none;
}

.markdown-body .task-list-item+.task-list-item {
  margin-top: 3px;
}

.markdown-body .task-list-item input {
  margin: 0 4px 0.25em -20px;
  vertical-align: middle;
}

/* Media */
@media only screen and (min-width: 480px) {
  .markdown-body {
    font-size:14px;
  }
}

@media only screen and (min-width: 768px) {
  .markdown-body {
    font-size:16px;
  }
}

@media print {
  .markdown-body * {
    background: transparent !important;
    color: black !important;
    filter:none !important;
    -ms-filter: none !important;
  }

  .markdown-body {
    font-size:12pt;
    max-width:100%;
    outline:none;
    border: 0;
  }

  .markdown-body a,
  .markdown-body a:visited {
    text-decoration: underline;
  }

  .markdown-body .headeranchor-link {
    display: none;
  }

  .markdown-body a[href]:after {
    content: " (" attr(href) ")";
  }

  .markdown-body abbr[title]:after {
    content: " (" attr(title) ")";
  }

  .markdown-body .ir a:after,
  .markdown-body a[href^="javascript:"]:after,
  .markdown-body a[href^="#"]:after {
    content: "";
  }

  .markdown-body pre {
    white-space: pre;
    white-space: pre-wrap;
    word-wrap: break-word;
  }

  .markdown-body pre,
  .markdown-body blockquote {
    border: 1px solid #999;
    padding-right: 1em;
    page-break-inside: avoid;
  }

  .markdown-body .progress,
  .markdown-body .progress-bar {
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    box-shadow: none;
  }

  .markdown-body .progress {
    border: 1px solid #ddd;
  }

  .markdown-body .progress-bar {
    height: 22px;
    border-right: 1px solid #ddd;
  }

  .markdown-body tr,
  .markdown-body img {
    page-break-inside: avoid;
  }

  .markdown-body img {
    max-width: 100% !important;
  }

  .markdown-body p,
  .markdown-body h2,
  .markdown-body h3 {
    orphans: 3;
    widows: 3;
  }

  .markdown-body h2,
  .markdown-body h3 {
    page-break-after: avoid;
  }
}
</style><title>linux-kernel-module-programming-guide</title></head><body><article class="markdown-body"><h1 id="linux-kernel-module-programming-guide"><a href="http://www.tldp.org/LDP/lkmpg/2.6/html/index.html">Linux Kernel Module Programming Guide</a></h1>
<p>Peter Jay Salzman<br />
Michael Burian<br />
Ori Pomerantz<br />
<a href="http://www.tldp.org/LDP/lkmpg/2.6/html/ln16.html">Copyright</a> © 2001 Peter Jay Salzman</p>
<p>2007-05-18 ver 2.6.4</p>
<hr />
<div class="toc">
<ul>
<li><a href="#linux-kernel-module-programming-guide">Linux Kernel Module Programming Guide</a><ul>
<li><a href="#foreword">Foreword</a><ul>
<li><a href="#1-authorship">1. Authorship</a></li>
<li><a href="#2-versioning-and-notes">2. Versioning and Notes</a></li>
<li><a href="#3-acknowledgements">3. Acknowledgements</a></li>
</ul>
</li>
<li><a href="#chapter-1-introduction">Chapter 1. Introduction</a><ul>
<li><a href="#11-what-is-a-kernel-module">1.1. What Is A Kernel Module?</a></li>
<li><a href="#12-how-do-modules-get-into-the-kernel">1.2. How Do Modules Get Into The Kernel?</a><ul>
<li><a href="#121-before-we-begin">1.2.1. Before We Begin</a><ul>
<li><a href="#1211-modversioning">1.2.1.1. Modversioning</a></li>
<li><a href="#1212-using-x">1.2.1.2. Using X</a></li>
<li><a href="#1213-compiling-issues-and-kernel-version">1.2.1.3. Compiling Issues and Kernel Version</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#chapter-2-hello-world">Chapter 2. Hello World</a><ul>
<li><a href="#21-hello-world-part-1-the-simplest-module">2.1. Hello, World (part 1): The Simplest Module</a><ul>
<li><a href="#211-introducing-printk">2.1.1. Introducing printk()</a></li>
</ul>
</li>
<li><a href="#22-compiling-kernel-modules">2.2. Compiling Kernel Modules</a></li>
<li><a href="#23-hello-world-part-2">2.3. Hello World (part 2)</a></li>
<li><a href="#24-hello-world-part-3-the-__init-and-__exit-macros">2.4. Hello World (part 3): The __init and __exit Macros</a></li>
<li><a href="#25-hello-world-part-4-licensing-and-module-documentation">2.5. Hello World (part 4): Licensing and Module Documentation</a></li>
<li><a href="#26-passing-command-line-arguments-to-a-module">2.6. Passing Command Line Arguments to a Module</a></li>
<li><a href="#27-modules-spanning-multiple-files">2.7. Modules Spanning Multiple Files</a></li>
<li><a href="#28-building-modules-for-a-precompiled-kernel">2.8. Building modules for a precompiled kernel</a></li>
</ul>
</li>
<li><a href="#chapter-3-preliminaries">Chapter 3. Preliminaries</a><ul>
<li><a href="#31-modules-vs-programs">3.1. Modules vs Programs</a><ul>
<li><a href="#311-how-modules-begin-and-end">3.1.1. How modules begin and end</a></li>
<li><a href="#312-functions-available-to-modules">3.1.2. Functions available to modules</a></li>
<li><a href="#313-user-space-vs-kernel-space">3.1.3. User Space vs Kernel Space</a></li>
<li><a href="#314-name-space">3.1.4. Name Space</a></li>
<li><a href="#315-code-space">3.1.5. Code space</a></li>
<li><a href="#316-device-drivers">3.1.6. Device Drivers</a><ul>
<li><a href="#3161-major-and-minor-numbers">3.1.6.1. Major and Minor Numbers</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><a href="#chapter-4-character-device-files">Chapter 4. Character Device Files</a><ul>
<li><a href="#41-character-device-drivers">4.1. Character Device Drivers</a><ul>
<li><a href="#411-the-file_operations-structure">4.1.1. The file_operations Structure</a></li>
<li><a href="#412-the-structure">4.1.2. The structure</a></li>
<li><a href="#413-registering-a-device">4.1.3. Registering A Device</a></li>
<li><a href="#414-unregistering-a-device">4.1.4. Unregistering A Device</a></li>
<li><a href="#415-chardevc">4.1.5. chardev.c</a></li>
<li><a href="#416-writing-modules-for-multiple-kernel-versions">4.1.6. Writing Modules for Multiple Kernel Versions</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#chapter-5-the-proc-file-system">Chapter 5. The /proc File System</a><ul>
<li><a href="#51-the-proc-file-system">5.1. The /proc File System</a></li>
<li><a href="#52-read-and-write-a-proc-file">5.2. Read and Write a /proc File</a></li>
<li><a href="#53-manage-proc-file-with-standard-filesystem">5.3. Manage /proc file with standard filesystem</a></li>
<li><a href="#54-manage-proc-file-with-seq_file">5.4. Manage /proc file with seq_file</a></li>
</ul>
</li>
<li><a href="#chapter-6-using-proc-for-input">Chapter 6. Using /proc For Input</a><ul>
<li><a href="#61-todo-write-a-chapter-about-sysfs">6.1. TODO: Write a chapter about sysfs</a></li>
</ul>
</li>
<li><a href="#chapter-7-talking-to-device-files">Chapter 7. Talking To Device Files</a><ul>
<li><a href="#71-talking-to-device-files-writes-and-ioctls">7.1. Talking to Device Files (writes and IOCTLs)</a></li>
</ul>
</li>
<li><a href="#chapter-8-system-calls">Chapter 8. System Calls</a><ul>
<li><a href="#81-system-calls">8.1. System Calls</a></li>
</ul>
</li>
<li><a href="#chapter-9-blocking-processes">Chapter 9. Blocking Processes</a><ul>
<li><a href="#91-blocking-processes">9.1. Blocking Processes</a></li>
</ul>
</li>
<li><a href="#chapter-10-replacing-printks">Chapter 10. Replacing Printks</a><ul>
<li><a href="#101-replacing-printk">10.1. Replacing printk</a></li>
<li><a href="#102-flashing-keyboard-leds">10.2. Flashing keyboard LEDs</a></li>
</ul>
</li>
<li><a href="#chapter-11-scheduling-tasks">Chapter 11. Scheduling Tasks</a><ul>
<li><a href="#111-scheduling-tasks">11.1. Scheduling Tasks</a></li>
</ul>
</li>
<li><a href="#chapter-12-interrupt-handlers">Chapter 12. Interrupt Handlers</a><ul>
<li><a href="#121-interrupt-handlers">12.1. Interrupt Handlers</a><ul>
<li><a href="#1211-interrupt-handlers">12.1.1. Interrupt Handlers</a></li>
<li><a href="#1212-keyboards-on-the-intel-architecture">12.1.2. Keyboards on the Intel Architecture</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#chapter-13-symmetric-multi-processing">Chapter 13. Symmetric Multi Processing</a><ul>
<li><a href="#131-symmetrical-multi-processing">13.1. Symmetrical Multi-Processing</a></li>
</ul>
</li>
<li><a href="#chapter-14-common-pitfalls">Chapter 14. Common Pitfalls</a><ul>
<li><a href="#141-common-pitfalls">14.1. Common Pitfalls</a></li>
</ul>
</li>
<li><a href="#a-changes-20-to-22">A. Changes: 2.0 To 2.2</a><ul>
<li><a href="#a11-changes-between-24-and-26">A.1.1. Changes between 2.4 and 2.6</a></li>
</ul>
</li>
<li><a href="#b-where-to-go-from-here">B. Where To Go From Here</a><ul>
<li><a href="#b1-where-from-here">B.1. Where From Here?</a></li>
</ul>
</li>
<li><a href="#doc-index">Doc Index</a></li>
</ul>
</li>
</ul>
</div>
<h2 id="foreword"><a name="user-content-foreword" href="#foreword" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Foreword</h2>
<h3 id="1-authorship"><a name="user-content-1-authorship" href="#1-authorship" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1. Authorship</h3>
<p>The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels.</p>
<h3 id="2-versioning-and-notes"><a name="user-content-2-versioning-and-notes" href="#2-versioning-and-notes" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2. Versioning and Notes</h3>
<p>The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch of the LKMPG for each new stable kernel version. So version LKMPG 2.4.x will address Linux kernel 2.4 and LKMPG 2.6.x will address Linux kernel 2.6. No attempt will be made to archive historical information; a person wishing this information should read the appropriately versioned LKMPG.</p>
<p>The source code and discussions should apply to most architectures, but I can&rsquo;t promise anything. One exception is <a href="#chapter 12">Chapter 12</a>, Interrupt Handlers, which should not work on any architecture except for x86.</p>
<h3 id="3-acknowledgements"><a name="user-content-3-acknowledgements" href="#3-acknowledgements" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3. Acknowledgements</h3>
<p>The following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon and Horst Schirmeier.</p>
<h2 id="chapter-1-introduction"><a name="user-content-chapter-1-introduction" href="#chapter-1-introduction" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 1. Introduction</h2>
<h3 id="11-what-is-a-kernel-module"><a name="user-content-11-what-is-a-kernel-module" href="#11-what-is-a-kernel-module" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.1. What Is A Kernel Module?</h3>
<p>So, you want to write a kernel module. You know C, you&rsquo;ve written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot.</p>
<p>What exactly is a kernel module? Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system. Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality.</p>
<h3 id="12-how-do-modules-get-into-the-kernel"><a name="user-content-12-how-do-modules-get-into-the-kernel" href="#12-how-do-modules-get-into-the-kernel" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.2. How Do Modules Get Into The Kernel?</h3>
<p>You can see what modules are already loaded into the kernel by running lsmod, which gets its information by reading the file /proc/modules.</p>
<p>How do these modules find their way into the kernel? When the kernel needs a feature that is not resident in the kernel, the kernel module daemon kmod<sup id="fnref:1"><a class="footnote-ref" href="#fn:1" rel="footnote">1</a></sup>execs modprobe to load the module in. modprobe is passed a string in one of two forms:</p>
<ul>
<li>A module name like softdog or ppp.</li>
<li>A more generic identifier like char-major-10-30.</li>
</ul>
<p>If modprobe is handed a generic identifier, it first looks for that string in the file <code>/etc/modprobe.conf</code><sup id="fnref:2"><a class="footnote-ref" href="#fn:2" rel="footnote">2</a></sup>. If it finds an alias line like:</p>
<pre><code>alias char-major-10-30 softdog
</code></pre>

<p>it knows that the generic identifier refers to the module softdog.ko.</p>
<p>Next, modprobe looks through the file /lib/modules/version/modules.dep, to see if other modules must be loaded before the requested module may be loaded. This file is created by depmod -a and contains module dependencies. For example, msdos.ko requires the fat.ko module to be already loaded into the kernel. The requested module has a dependency on another module if the other module defines symbols    (variables or functions) that the requested module uses.</p>
<p>Lastly, modprobe uses insmod to first load any prerequisite modules into the kernel, and then the requested module. modprobe directs insmod to <code>/lib/modules/version/</code><sup id="fnref:3"><a class="footnote-ref" href="#fn:3" rel="footnote">3</a></sup>, the standard directory for modules. insmod is intended to be fairly dumb about the location of modules, whereas modprobe is aware of the default location of modules, knows how to figure out the dependencies and load the modules in the right order. So for example,   if you wanted to load the msdos module, you&rsquo;d have to either run:</p>
<pre><code>insmod /lib/modules/2.6.11/kernel/fs/fat/fat.ko
insmod /lib/modules/2.6.11/kernel/fs/msdos/msdos.ko
</code></pre>

<p>or:</p>
<pre><code>modprobe msdos
</code></pre>

<p>What we&rsquo;ve seen here is: insmod requires you to pass it the full pathname and to insert the modules in the right order, while modprobe just takes the name, without any extension, and figures out all it needs to know by parsing /lib/modules/version/modules.dep.</p>
<p>Linux distros provide modprobe, insmod and depmod as a package called module-init-tools. In previous versions that package was called modutils. Some distros also set up some wrappers that allow both packages to be installed in parallel and do the right thing in order to be able to deal with 2.4 and 2.6 kernels. Users should not need to care about the details, as long as they&rsquo;re running recent versions of those tools.</p>
<p>Now you know how modules get into the kernel. There&rsquo;s a bit more to the story if you want to write your own modules which depend on other modules (we calling this `stacking modules&rsquo;). But this will have to wait for a future chapter. We have a lot to cover before addressing this relatively high-level issue.</p>
<h4 id="121-before-we-begin"><a name="user-content-121-before-we-begin" href="#121-before-we-begin" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.2.1. Before We Begin</h4>
<p>Before we delve into code, there are a few issues we need to cover. Everyone&rsquo;s system is different and everyone has their own groove. Getting your first &ldquo;hello world&rdquo; program to compile and load correctly can sometimes be a trick. Rest assured, after you get over the initial hurdle of doing it for the first time, it will be smooth sailing thereafter.</p>
<h5 id="1211-modversioning"><a name="user-content-1211-modversioning" href="#1211-modversioning" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.2.1.1. Modversioning</h5>
<p>A module compiled for one kernel won&rsquo;t load if you boot a different kernel unless you enable CONFIG_MODVERSIONS in the kernel. We won&rsquo;t go into module versioning until later in this guide. Until we cover modversions, the examples in the guide may not work if you&rsquo;re running a kernel with modversioning turned on. However, most stock Linux distro kernels come with it turned on. If you&rsquo;re having trouble loading the modules because of versioning errors, compile a kernel with modversioning turned off.</p>
<p><span id = "Section 1.2.1.2"></span></p>
<h5 id="1212-using-x"><a name="user-content-1212-using-x" href="#1212-using-x" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.2.1.2. Using X</h5>
<p>It is highly recommended that you type in, compile and load all the examples this guide discusses. It&rsquo;s also highly recommended you do this from a console. You should not be working on this stuff in X.</p>
<p>Modules can&rsquo;t print to the screen like printf() can, but they can log information and warnings, which ends up being printed on your screen, but only on a console. If you insmod a module from an xterm, the information and warnings will be logged, but only to your log files. You won&rsquo;t see it unless you look through your log files. To have immediate access to this information, do all your work from the console.</p>
<h5 id="1213-compiling-issues-and-kernel-version"><a name="user-content-1213-compiling-issues-and-kernel-version" href="#1213-compiling-issues-and-kernel-version" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>1.2.1.3. Compiling Issues and Kernel Version</h5>
<p>Very often, Linux distros will distribute kernel source that has been patched in various non-standard ways, which may cause trouble.</p>
<p>A more common problem is that some Linux distros distribute incomplete kernel headers. You&rsquo;ll need to compile your code using various header files from the Linux kernel. Murphy&rsquo;s Law states that the headers that are missing are exactly the ones that you&rsquo;ll need for your module work.</p>
<p>To avoid these two problems, I highly recommend that you download, compile and boot into a fresh, stock Linux kernel which can be downloaded from any of the Linux kernel mirror sites. See the Linux Kernel HOWTO for more details.</p>
<p>Ironically, this can also cause a problem. By default, gcc on your system may look for the kernel headers in their default location rather than where you installed the new copy of the kernel (usually in <code>/usr/src/</code>. This can be fixed by using gcc&rsquo;s -I switch.</p>
<p><strong> Notes </strong>:</p>
<h2 id="chapter-2-hello-world"><a name="user-content-chapter-2-hello-world" href="#chapter-2-hello-world" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 2. Hello World</h2>
<h3 id="21-hello-world-part-1-the-simplest-module"><a name="user-content-21-hello-world-part-1-the-simplest-module" href="#21-hello-world-part-1-the-simplest-module" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.1. Hello, World (part 1): The Simplest Module</h3>
<p>When the first caveman programmer chiseled the first program on the walls of the first cave computer, it was a program to paint the string <code>Hello, world</code> in Antelope pictures. Roman programming textbooks began with the <code>Salut, Mundi</code> program. I don&rsquo;t know what happens to people who break with this tradition, but I think it&rsquo;s safer not to find out. We&rsquo;ll start with a series of hello world programs that demonstrate the different aspects of the basics of writing a kernel module.</p>
<p>Here&rsquo;s the simplest module possible. Don&rsquo;t compile it yet; we&rsquo;ll cover module compilation in the next section.</p>
<p>Example 2-1. hello-1.c</p>
<pre><code>/*  
 *  hello-1.c - The simplest kernel module.
 */
#include &lt;linux/module.h&gt;   /* Needed by all modules */
#include &lt;linux/kernel.h&gt;   /* Needed for KERN_INFO */

int init_module(void)
{
    printk(KERN_INFO &quot;Hello world 1.\n&quot;);

    /* 
     * A non 0 return means init_module failed; module can't be loaded. 
     */
    return 0;
}

void cleanup_module(void)
{
    printk(KERN_INFO &quot;Goodbye world 1.\n&quot;);
}
</code></pre>

<p>Kernel modules must have at least two functions: a &ldquo;start&rdquo; (initialization) function called init_module() which is called when the module is insmoded into the kernel, and an &ldquo;end&rdquo; (cleanup) function called cleanup_module() which is called just before it is rmmoded. Actually, things have changed starting with kernel 2.3.13. You can now use whatever name you like for the start and end functions of a module, and you&rsquo;ll learn how to do this in <a href="#Section 2.3">Section 2.3</a>. In fact, the new method is the preferred method. However, many people still use <code>init_module()</code> and <code>cleanup_module()</code> for their start and end functions.</p>
<p>Typically, <code>init_module()</code> either registers a handler for something with the kernel, or it replaces one of the kernel functions with its own code (usually code to do something and then call the original function). The <code>cleanup_module()</code> function is supposed to undo whatever <code>init_module()</code> did, so the module can be unloaded safely.</p>
<p>Lastly, every kernel module needs to include <code>linux/module.h</code>. We needed to include <code>linux/kernel.h</code> only for the macro expansion for the <code>printk()</code> log level, KERN_ALERT, which you&rsquo;ll learn about in <a href="#Section 2.1.1">Section 2.1.1</a>.</p>
<p><span id = "Section 2.1.1"></span></p>
<h4 id="211-introducing-printk"><a name="user-content-211-introducing-printk" href="#211-introducing-printk" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.1.1. Introducing <code>printk()</code></h4>
<p>Despite what you might think, <code>printk()</code> was not meant to communicate information to the user, even though we used it for exactly this purpose in hello-1! It happens to be a logging mechanism for the kernel, and is used to log information or give warnings. Therefore, each printk() statement comes with a priority, which is the &lt;1&gt; and <code>KERN_ALERT</code> you see. There are 8 priorities and the kernel has macros for them, so you don&rsquo;t have to use cryptic numbers, and you can view them (and their meanings) in <code>linux/kernel</code>.h. If you don&rsquo;t specify a priority level, the default priority, <code>DEFAULT_MESSAGE_LOGLEVEL</code>, will be used.</p>
<p>Take time to read through the priority macros. The header file also describes what each priority means. In practise, don&rsquo;t use number, like &lt;4&gt;. Always use the macro, like <code>KERN_WARNING</code>.</p>
<p>If the priority is less than int console_loglevel, the message is printed on your current terminal. If both syslogd and klogd are running, then the message will also get appended to <code>/var/log/messages</code>, whether it got printed to the console or not. We use a high priority, like <code>KERN_ALERT</code>, to make sure the <code>printk()</code> messages get printed to your console rather than just logged to your logfile. When you write real modules, you&rsquo;ll want to use priorities that are meaningful for the situation at hand.</p>
<h3 id="22-compiling-kernel-modules"><a name="user-content-22-compiling-kernel-modules" href="#22-compiling-kernel-modules" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.2. Compiling Kernel Modules</h3>
<p>Kernel modules need to be compiled a bit differently from regular userspace apps. Former kernel versions required us to care much about these settings, which are usually stored in Makefiles. Although hierarchically organized, many redundant settings accumulated in    sublevel Makefiles and made them large and rather difficult to maintain. Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism. To learn more on how to compile modules which are not part of the official kernel (such as all the examples you&rsquo;ll find in this guide), see file <code>linux/Documentation/kbuild/modules.txt</code>.</p>
<p>So, let&rsquo;s look at a simple Makefile for compiling a module named <code>hello-1.c</code>:</p>
<p>Example 2-2. Makefile for a basic kernel module</p>
<pre><code>obj-m += hello-1.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code></pre>

<p>From a technical point of view just the first line is really necessary, the &ldquo;all&rdquo; and &ldquo;clean&rdquo; targets were added for pure convenience.</p>
<p>Now you can compile the module by issuing the command make . You should obtain an output which resembles the following:</p>
<pre><code>hostname:~/lkmpg-examples/02-HelloWorld# make
make -C /lib/modules/2.6.11/build M=/root/lkmpg-examples/02-HelloWorld modules
make[1]: Entering directory `/usr/src/linux-2.6.11'
  CC [M]  /root/lkmpg-examples/02-HelloWorld/hello-1.o
 Building modules, stage 2.
  MODPOST
  CC      /root/lkmpg-examples/02-HelloWorld/hello-1.mod.o
  LD [M]  /root/lkmpg-examples/02-HelloWorld/hello-1.ko
make[1]: Leaving directory `/usr/src/linux-2.6.11'
hostname:~/lkmpg-examples/02-HelloWorld#
</code></pre>

<p>Note that kernel 2.6 introduces a new file naming convention: kernel modules now have a .ko extension (in place of the old .o extension) which easily distinguishes them from conventional object files. The reason for this is that they contain an additional .modinfo section that where additional information about the module is kept. We&rsquo;ll soon see what this information is good for.</p>
<p>Use modinfo hello-*.ko to see what kind of information it is.</p>
<pre><code>hostname:~/lkmpg-examples/02-HelloWorld# modinfo hello-1.ko
filename:       hello-1.ko
vermagic:       2.6.11 preempt PENTIUMII 4KSTACKS gcc-3.3
depends:
</code></pre>

<p>Nothing spectacular, so far. That changes once we&rsquo;re using modinfo on one of our the later examples, <code>hello-5.ko</code> .</p>
<pre><code>hostname:~/lkmpg-examples/02-HelloWorld# modinfo hello-5.ko
filename:       hello-5.ko
license:        GPL
author:         Peter Jay Salzman
vermagic:       2.6.11 preempt PENTIUMII 4KSTACKS gcc-3.3
depends:
parm:           myintArray:An array of integers (array of int)
parm:           mystring:A character string (charp)
parm:           mylong:A long integer (long)
parm:           myint:An integer (int)
parm:           myshort:A short integer (short)
hostname:~/lkmpg-examples/02-HelloWorld# 
</code></pre>

<p>Lot&rsquo;s of useful information to see here. An author string for bugreports, license information, even a short description of the parameters it accepts.</p>
<p>Additional details about Makefiles for kernel modules are available in <code>linux/Documentation/kbuild/makefiles.txt</code>. Be sure to read this and the related files before starting to hack Makefiles. It&rsquo;ll probably save you lots of work.</p>
<p>Now it is time to insert your freshly-compiled module it into the kernel with insmod ./hello-1.ko (ignore anything you see about tainted kernels; we&rsquo;ll cover that shortly).</p>
<p>All modules loaded into the kernel are listed in <code>/proc/modules</code>. Go ahead and cat that file to see that your module is really a part of the kernel. Congratulations, you are now the author of Linux kernel code! When the novelty wears off, remove your module from the kernel by using rmmod hello-1. Take a look at <code>/var/log/messages</code> just to see that it got logged to your system logfile.</p>
<p>Here&rsquo;s another exercise for the reader. See that comment above the return statement in <code>init_module()</code>? Change the return value to something negative, recompile and load the module again. What happens?</p>
<p><span id ="Section 2.3"> </span></p>
<h3 id="23-hello-world-part-2"><a name="user-content-23-hello-world-part-2" href="#23-hello-world-part-2" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.3. Hello World (part 2)</h3>
<p>As of Linux 2.4, you can rename the init and cleanup functions of your modules; they no longer have to be called <code>init_module()</code> and <code>cleanup_module()</code> respectively. This is done with the <code>module_init()</code> and <code>module_exit()</code> macros. These macros are defined in <code>linux/init.h</code>. The only caveat is that your init and cleanup functions must be defined before calling    the macros, otherwise you&rsquo;ll get compilation errors. Here&rsquo;s an example of this technique:</p>
<p>Example 2-3. hello-2.c</p>
<pre><code>/*  
 *  hello-2.c - Demonstrating the module_init() and module_exit() macros.
 *  This is preferred over using init_module() and cleanup_module().
 */
#include &lt;linux/module.h&gt;   /* Needed by all modules */
#include &lt;linux/kernel.h&gt;   /* Needed for KERN_INFO */
#include &lt;linux/init.h&gt;     /* Needed for the macros */

static int __init hello_2_init(void)
{
    printk(KERN_INFO &quot;Hello, world 2\n&quot;);
    return 0;
}

static void __exit hello_2_exit(void)
{
    printk(KERN_INFO &quot;Goodbye, world 2\n&quot;);
}

module_init(hello_2_init);
module_exit(hello_2_exit);
</code></pre>

<p>So now we have two real kernel modules under our belt. Adding another module is as simple as this:</p>
<p>Example 2-4. Makefile for both our modules<br />
<pre><code>obj-m += hello-1.o
obj-m += hello-2.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code></pre></p>
<p>Now have a look at <code>linux/drivers/char/Makefile</code> for a real world example. As you can see, some things get hardwired into the kernel (obj-y) but where are all those obj-m gone? Those familiar with shell scripts will easily be able to spot them. For those not, the <code>obj-$(CONFIG_FOO)</code> entries you see everywhere expand into obj-y or obj-m, depending on whether the CONFIG_FOO variable has been set to y or m. While we are at it, those were exactly the kind of variables that you have set in the <code>linux/.config</code> file, the last time when you said make menuconfig or something like that.</p>
<h3 id="24-hello-world-part-3-the-__init-and-__exit-macros"><a name="user-content-24-hello-world-part-3-the-__init-and-__exit-macros" href="#24-hello-world-part-3-the-__init-and-__exit-macros" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.4. Hello World (part 3): The <code>__init</code> and <code>__exit</code> Macros</h3>
<p>This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The <code>__init</code> macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.</p>
<p>There is also an <code>__initdata</code> which works similarly to <code>__init</code> but for init variables rather than functions.</p>
<p>The <code>__exit</code> macro causes the omission of the function when the module is built into the kernel, and like <code>__exit</code>, has no effect for loadable modules. Again, if you consider when the cleanup function runs, this makes complete sense; built-in drivers don&rsquo;t need a cleanup function, while loadable modules do.</p>
<p>These macros are defined in <code>linux/init.h</code> and serve to free up kernel memory. When you boot your kernel and see something like <code>Freeing unused kernel memory: 236k freed</code>, this is precisely what the kernel is freeing.</p>
<p>Example 2-5. hello-3.c</p>
<pre><code>/*  
 *  hello-3.c - Illustrating the __init, __initdata and __exit macros.
 */
#include &lt;linux/module.h&gt;   /* Needed by all modules */
#include &lt;linux/kernel.h&gt;   /* Needed for KERN_INFO */
#include &lt;linux/init.h&gt;     /* Needed for the macros */

static int hello3_data __initdata = 3;

static int __init hello_3_init(void)
{
    printk(KERN_INFO &quot;Hello, world %d\n&quot;, hello3_data);
    return 0;
}

static void __exit hello_3_exit(void)
{
    printk(KERN_INFO &quot;Goodbye, world 3\n&quot;);
}

module_init(hello_3_init);
module_exit(hello_3_exit);
</code></pre>

<h3 id="25-hello-world-part-4-licensing-and-module-documentation"><a name="user-content-25-hello-world-part-4-licensing-and-module-documentation" href="#25-hello-world-part-4-licensing-and-module-documentation" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.5. Hello World (part 4): Licensing and Module Documentation</h3>
<p>If you&rsquo;re running kernel 2.4 or later, you might have noticed something like this when you loaded   proprietary modules:</p>
<pre><code># insmod xxxxxx.o
Warning: loading xxxxxx.ko will taint the kernel: no license
  See http://www.tux.org/lkml/#export-tainted for information about tainted modules
Module xxxxxx loaded, with warnings
</code></pre>

<p>In kernel 2.4 and later, a mechanism was devised to identify code licensed under the GPL (and friends) so people can be warned that the code is non open-source. This is accomplished by the <code>MODULE_LICENSE()</code> macro which is demonstrated in the next piece of code. By setting the license to GPL, you can keep the warning from being printed. This license mechanism is defined and documented in <code>linux/module.h</code>:</p>
<pre><code>/*
 * The following license idents are currently accepted as indicating free
 * software modules
 *
 *  &quot;GPL&quot;               [GNU Public License v2 or later]
 *  &quot;GPL v2&quot;            [GNU Public License v2]
 *  &quot;GPL and additional rights&quot; [GNU Public License v2 rights and more]
 *  &quot;Dual BSD/GPL&quot;          [GNU Public License v2
 *                   or BSD license choice]
 *  &quot;Dual MIT/GPL&quot;          [GNU Public License v2
 *                   or MIT license choice]
 *  &quot;Dual MPL/GPL&quot;          [GNU Public License v2
 *                   or Mozilla license choice]
 *
 * The following other idents are available
 *
 *  &quot;Proprietary&quot;           [Non free products]
 *
 * There are dual licensed components, but when running with Linux it is the
 * GPL that is relevant so this is a non issue. Similarly LGPL linked with GPL
 * is a GPL combined work.
 *
 * This exists for several reasons
 * 1.   So modinfo can show license info for users wanting to vet their setup 
 *  is free
 * 2.   So the community can ignore bug reports including proprietary modules
 * 3.   So vendors can do likewise based on their own policies
 */
</code></pre>

<p>Similarly, <code>MODULE_DESCRIPTION()</code> is used to describe what the module does, <code>MODULE_AUTHOR()</code> declares the module&rsquo;s author, and <code>MODULE_SUPPORTED_DEVICE()</code> declares what types of devices the module supports.</p>
<p>These macros are all defined in <code>linux/module.h</code> and aren&rsquo;t used by the kernel itself. They&rsquo;re simply for documentation and can be viewed by a tool like objdump. As an exercise to the reader, try and search fo these macros in <code>linux/drivers</code> to see how module authors use these macros to document their modules.</p>
<p>I&rsquo;d recommend to use something like <code>grep -inr MODULE_AUTHOR * in /usr/src/linux-2.6.x/</code>. People unfamiliar with command line tools will probably like some web base solution, search for sites that offer kernel trees that got indexed with LXR. (or setup it up on your local machine).</p>
<p>Users of traditional Unix editors, like emacs or vi will also find tag files useful. They can be generated by make tags or make TAGS in <code>/usr/src/linux-2.6.x/</code>. Once you&rsquo;ve got such a tagfile in your kerneltree you can put the cursor on some function call and use some key combination to directly jump to the definition function.</p>
<p>Example 2-6. hello-4.c</p>
<pre><code>/*  
 *  hello-4.c - Demonstrates module documentation.
 */
#include &lt;linux/module.h&gt;   /* Needed by all modules */
#include &lt;linux/kernel.h&gt;   /* Needed for KERN_INFO */
#include &lt;linux/init.h&gt;     /* Needed for the macros */
#define DRIVER_AUTHOR &quot;Peter Jay Salzman &lt;p@dirac.org&gt;&quot;
#define DRIVER_DESC   &quot;A sample driver&quot;

static int __init init_hello_4(void)
{
    printk(KERN_INFO &quot;Hello, world 4\n&quot;);
    return 0;
}

static void __exit cleanup_hello_4(void)
{
    printk(KERN_INFO &quot;Goodbye, world 4\n&quot;);
}

module_init(init_hello_4);
module_exit(cleanup_hello_4);

/*  
 *  You can use strings, like this:
 */

/* 
 * Get rid of taint message by declaring code as GPL. 
 */
MODULE_LICENSE(&quot;GPL&quot;);

/*
 * Or with defines, like this:
 */
MODULE_AUTHOR(DRIVER_AUTHOR);   /* Who wrote this module? */
MODULE_DESCRIPTION(DRIVER_DESC);    /* What does this module do */

/*  
 *  This module uses /dev/testdevice.  The MODULE_SUPPORTED_DEVICE macro might
 *  be used in the future to help automatic configuration of modules, but is 
 *  currently unused other than for documentation purposes.
 */
MODULE_SUPPORTED_DEVICE(&quot;testdevice&quot;);
</code></pre>

<h3 id="26-passing-command-line-arguments-to-a-module"><a name="user-content-26-passing-command-line-arguments-to-a-module" href="#26-passing-command-line-arguments-to-a-module" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.6. Passing Command Line Arguments to a Module</h3>
<p>Modules can take command line arguments, but not with the <code>argc/argv</code> you might be used to.</p>
<p>To allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the <code>module_param()</code> macro, (defined in <code>linux/moduleparam.h</code>) to set the mechanism up. At runtime, insmod will fill the variables with any command line arguments that are given, like <code>./insmod mymodule.ko myvariable=5</code>. The variable declarations and macros should be placed at the beginning of the module for clarity. The example code should clear up my admittedly lousy explanation.</p>
<p>The <code>module_param()</code> macro takes 3 arguments: the name of the variable, its type and permissions for the corresponding file in sysfs. Integer types can be signed as usual or unsigned. If you&rsquo;d like to use arrays of integers or strings see <code>module_param_array()</code> and <code>module_param_string()</code>.</p>
<pre><code>int myint = 3;
module_param(myint, int, 0);
</code></pre>

<p>Arrays are supported too, but things are a bit different now than they were in the 2.4. days. To keep track of the number of parameters you need to pass a pointer to a count variable as third parameter. At your option, you could also ignore the count and pass NULL instead. We show both possibilities here:</p>
<pre><code>int myintarray[2];
module_param_array(myintarray, int, NULL, 0); /* not interested in count */

int myshortarray[4];
int count;
module_parm_array(myshortarray, short, , 0); /* put count into &quot;count&quot; variable */
</code></pre>

<p>A good use for this is to have the module variable&rsquo;s default values set, like an port or IO address. If the variables contain the default values, then perform autodetection (explained elsewhere). Otherwise, keep the current value. This will be made clear later on.</p>
<p>Lastly, there&rsquo;s a macro function, MODULE_PARM_DESC(), that is used to document arguments that the module can take. It takes two parameters: a variable name and a free form string describing that variable.</p>
<p>Example 2-7. hello-5.c<br />
<pre><code>/*
 *  hello-5.c - Demonstrates command line argument passing to a module.
 */
#include &lt;linux/module.h&gt;
#include &lt;linux/moduleparam.h&gt;
#include &lt;linux/kernel.h&gt;
#include &lt;linux/init.h&gt;
#include &lt;linux/stat.h&gt;

MODULE_LICENSE(&quot;GPL&quot;);
MODULE_AUTHOR(&quot;Peter Jay Salzman&quot;);

static short int myshort = 1;
static int myint = 420;
static long int mylong = 9999;
static char *mystring = &quot;blah&quot;;
static int myintArray[2] = { -1, -1 };
static int arr_argc = 0;

/* 
 * module_param(foo, int, 0000)
 * The first param is the parameters name
 * The second param is it's data type
 * The final argument is the permissions bits, 
 * for exposing parameters in sysfs (if non-zero) at a later stage.
 */

module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
MODULE_PARM_DESC(myshort, &quot;A short integer&quot;);
module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
MODULE_PARM_DESC(myint, &quot;An integer&quot;);
module_param(mylong, long, S_IRUSR);
MODULE_PARM_DESC(mylong, &quot;A long integer&quot;);
module_param(mystring, charp, 0000);
MODULE_PARM_DESC(mystring, &quot;A character string&quot;);

/*
 * module_param_array(name, type, num, perm);
 * The first param is the parameter's (in this case the array's) name
 * The second param is the data type of the elements of the array
 * The third argument is a pointer to the variable that will store the number 
 * of elements of the array initialized by the user at module loading time
 * The fourth argument is the permission bits
 */
module_param_array(myintArray, int, &amp;arr_argc, 0000);
MODULE_PARM_DESC(myintArray, &quot;An array of integers&quot;);

static int __init hello_5_init(void)
{
    int i;
    printk(KERN_INFO &quot;Hello, world 5\n=============\n&quot;);
    printk(KERN_INFO &quot;myshort is a short integer: %hd\n&quot;, myshort);
    printk(KERN_INFO &quot;myint is an integer: %d\n&quot;, myint);
    printk(KERN_INFO &quot;mylong is a long integer: %ld\n&quot;, mylong);
    printk(KERN_INFO &quot;mystring is a string: %s\n&quot;, mystring);
    for (i = 0; i &lt; (sizeof myintArray / sizeof (int)); i++)
    {
        printk(KERN_INFO &quot;myintArray[%d] = %d\n&quot;, i, myintArray[i]);
    }
    printk(KERN_INFO &quot;got %d arguments for myintArray.\n&quot;, arr_argc);
    return 0;
}

static void __exit hello_5_exit(void)
{
    printk(KERN_INFO &quot;Goodbye, world 5\n&quot;);
}

module_init(hello_5_init);
module_exit(hello_5_exit);
</code></pre></p>
<p>I would recommend playing around with this code:</p>
<pre><code>satan# insmod hello-5.ko mystring=&quot;bebop&quot; mybyte=255 myintArray=-1
mybyte is an 8 bit integer: 255
myshort is a short integer: 1
myint is an integer: 20
mylong is a long integer: 9999
mystring is a string: bebop
myintArray is -1 and 420

satan# rmmod hello-5
Goodbye, world 5

satan# insmod hello-5.ko mystring=&quot;supercalifragilisticexpialidocious&quot; \
&gt; mybyte=256 myintArray=-1,-1
mybyte is an 8 bit integer: 0
myshort is a short integer: 1
myint is an integer: 20
mylong is a long integer: 9999
mystring is a string: supercalifragilisticexpialidocious
myintArray is -1 and -1

satan# rmmod hello-5
Goodbye, world 5

satan# insmod hello-5.ko mylong=hello
hello-5.o: invalid argument syntax for mylong: 'h'
</code></pre>

<h3 id="27-modules-spanning-multiple-files"><a name="user-content-27-modules-spanning-multiple-files" href="#27-modules-spanning-multiple-files" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.7. Modules Spanning Multiple Files</h3>
<p>Sometimes it makes sense to divide a kernel module between several source files.</p>
<p>Here&rsquo;s an example of such a kernel module.</p>
<p>Example 2-8. start.c</p>
<pre><code>/*
 *  start.c - Illustration of multi filed modules
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */

int init_module(void)
{
    printk(KERN_INFO &quot;Hello, world - this is the kernel speaking\n&quot;);
    return 0;
}
</code></pre>

<p>The next file:</p>
<p>Example 2-9. stop.c<br />
<pre><code>/*
 *  stop.c - Illustration of multi filed modules
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module  */

void cleanup_module()
{
    printk(KERN_INFO &quot;Short is the life of a kernel module\n&quot;);
}
</code></pre></p>
<p>And finally, the makefile:</p>
<p>Example 2-10. Makefile</p>
<pre><code>obj-m += hello-1.o
obj-m += hello-2.o
obj-m += hello-3.o
obj-m += hello-4.o
obj-m += hello-5.o
obj-m += startstop.o
startstop-objs := start.o stop.o

all:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules

clean:
    make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
</code></pre>

<p>This is the complete makefile for all the examples we&rsquo;ve seen so far. The first five lines are nothing special, but for the last example we&rsquo;ll need two lines. First we invent an object name for our combined module, second we tell make what object files are part of that module.</p>
<h3 id="28-building-modules-for-a-precompiled-kernel"><a name="user-content-28-building-modules-for-a-precompiled-kernel" href="#28-building-modules-for-a-precompiled-kernel" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>2.8. Building modules for a precompiled kernel</h3>
<p>Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features, such as forced module unloading (<code>MODULE_FORCE_UNLOAD</code>): when this option is enabled, you can force the kernel to unload a module even when it believes it is unsafe, via a rmmod -f module command. This option can save you a lot of time and a number of reboots during the development of a module.</p>
<p>Nevertheless, there is a number of cases in which you may want to load your module into a precompiled running kernel, such as the ones shipped with common Linux distributions, or a kernel you have compiled in the past. In certain circumstances you could require to compile and insert a module into a running kernel which you are not allowed to recompile, or on a machine that you prefer not to reboot. If you can&rsquo;t think of a case that will force you to use modules for a precompiled kernel you might want to skip this and treat the rest of this chapter as a big footnote.</p>
<p>Now, if you just install a kernel source tree, use it to compile your kernel module and you try to insert your module into the kernel, in most cases you would obtain an error as follows:</p>
<pre><code>insmod: error inserting 'poet_atkm.ko': -1 Invalid module format
</code></pre>

<p>Less cryptical information are logged to <code>/var/log/messages</code>:</p>
<pre><code>Jun  4 22:07:54 localhost kernel: poet_atkm: version magic '2.6.5-1.358custom 686 
REGPARM 4KSTACKS gcc-3.3' should be '2.6.5-1.358 686 REGPARM 4KSTACKS gcc-3.3'
</code></pre>

<p>In other words, your kernel refuses to accept your module because version strings (more precisely, version magics) do not match. Incidentally, version magics are stored in the module object in the form of a static string, starting with <code>vermagic</code>:. Version data are inserted in your module when it is linked against the <code>init/vermagic.o</code> file. To inspect version magics and other strings stored in a given module, issue the modinfo module.ko command:</p>
<pre><code>[root@pcsenonsrv 02-HelloWorld]# modinfo hello-4.ko 
license:        GPL
author:         Peter Jay Salzman &lt;p@dirac.org&gt;
description:    A sample driver
vermagic:       2.6.5-1.358 686 REGPARM 4KSTACKS gcc-3.3
depends:        
</code></pre>

<p>To overcome this problem we could resort to the &ndash;force-vermagic option, but this solution is potentially unsafe, and unquestionably inacceptable in production modules. Consequently, we want to compile our module in an environment which was identical to the one in which our precompiled kernel was built. How to do this, is the subject of the remainder of this chapter.</p>
<p>First of all, make sure that a kernel source tree is available, having exactly the same version as your current kernel. Then, find the configuration file which was used to compile your precompiled kernel. Usually, this is available in your current /boot directory, under a name like <code>config-2.6.x</code>. You may just want to copy it to your kernel source tree: </p>
<pre><code>cp /boot/config-`uname -r` /usr/src/linux-`uname -r`/.config
</code></pre>

<p>Let&rsquo;s focus again on the previous error message: a closer look at the version magic strings suggests that, even with two configuration files which are exactly the same, a slight difference in the version magic could be possible, and it is sufficient to prevent insertion of the module into the kernel. That slight difference, namely the custom string which appears in the module&rsquo;s version magic and not in the kernel&rsquo;s one, is due to a modification with respect to the original, in the makefile that some distribution include. Then, examine your <code>/usr/src/linux/Makefile</code>, and make sure that the specified version information matches exactly the one used for your current kernel. For example, you makefile could start as follows:</p>
<pre><code>VERSION = 2
PATCHLEVEL = 6
SUBLEVEL = 5
EXTRAVERSION = -1.358custom
...
</code></pre>

<p>In this case, you need to restore the value of symbol EXTRAVERSION to -1.358. We suggest to keep a backup copy of the makefile used to compile your kernel available in <code>/lib/modules/2.6.5-1.358/build</code>. A simple cp /lib/modules/<code>uname -r</code>/build/Makefile /usr/src/linux-<code>uname -r</code> should suffice. Additionally, if you already started a kernel build with the previous (wrong) Makefile, you should also rerun make, or directly modify symbol UTS_RELEASE in file <code>/usr/src/linux-2.6.x/include/linux/version.h</code> according to contents of file <code>/lib/modules/2.6.x/build/include/linux/version.h</code>, or overwrite the latter with the first.</p>
<p>Now, please run make to update configuration and version headers and objects:</p>
<pre><code>[root@pcsenonsrv linux-2.6.x]# make
CHK     include/linux/version.h
UPD     include/linux/version.h
SYMLINK include/asm -&gt; include/asm-i386
SPLIT   include/linux/autoconf.h -&gt; include/config/*
HOSTCC  scripts/basic/fixdep
HOSTCC  scripts/basic/split-include
HOSTCC  scripts/basic/docproc
HOSTCC  scripts/conmakehash
HOSTCC  scripts/kallsyms
CC      scripts/empty.o
...
</code></pre>

<p>If you do not desire to actually compile the kernel, you can interrupt the build process (CTRL-C) just after the SPLIT line, because at that time, the files you need will be are ready. Now you can turn back to the directory of your module and compile it: It will be built exactly according your current kernel settings, and it will load into it without any errors.</p>
<h2 id="chapter-3-preliminaries"><a name="user-content-chapter-3-preliminaries" href="#chapter-3-preliminaries" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 3. Preliminaries</h2>
<h3 id="31-modules-vs-programs"><a name="user-content-31-modules-vs-programs" href="#31-modules-vs-programs" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1. Modules vs Programs</h3>
<h4 id="311-how-modules-begin-and-end"><a name="user-content-311-how-modules-begin-and-end" href="#311-how-modules-begin-and-end" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.1. How modules begin and end</h4>
<p>A program usually begins with a <code>main()</code> function, executes a bunch of instructions and terminates upon completion of those instructions. Kernel modules work a bit differently. A module always begin with either the <code>init_module</code> or the function you specify with <code>module_init</code> call. This is the entry function for modules; it tells the kernel what functionality the module provides and sets up the kernel to run the module&rsquo;s functions when they&rsquo;re needed. Once it does this, entry function returns and the module does nothing until the kernel wants to do something with the code that the module provides.</p>
<p>All modules end by calling either <code>cleanup_module</code> or the function you specify with the <code>module_exit</code> call. This is the exit function for modules; it undoes whatever entry function did. It unregisters the functionality that the entry function registered.</p>
<p>Every module must have an entry function and an exit function. Since there&rsquo;s more than one way to specify entry and exit functions, I&rsquo;ll try my best to use the terms <code>entry function</code> and <code>exit function</code>, but if I slip and simply refer to them as <code>init_module</code> and <code>cleanup_module</code>, I think you&rsquo;ll know what I mean.</p>
<h4 id="312-functions-available-to-modules"><a name="user-content-312-functions-available-to-modules" href="#312-functions-available-to-modules" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.2. Functions available to modules</h4>
<p>Programmers use functions they don&rsquo;t define all the time. A prime example of this is <code>printf()</code>. You use these library functions which are provided by the standard C library, libc. The definitions for these functions don&rsquo;t actually enter your program until the linking stage, which insures that the code (for <code>printf()</code> for example) is available, and fixes the call instruction to point to that code.</p>
<p>Kernel modules are different here, too. In the hello world example, you might have noticed that we used a function, printk() but didn&rsquo;t include a standard I/O library. That&rsquo;s because modules are object files whose symbols get resolved upon insmod&rsquo;ing. The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel. If you&rsquo;re curious about what symbols have been exported by your kernel, take a look at <code>/proc/kallsyms</code>.</p>
<p>One point to keep in mind is the difference between library functions and system calls. Library functions are higher level, run completely in user space and provide a more convenient interface for the programmer to the functions that do the real work&mdash;system calls. System calls run in kernel mode on the user&rsquo;s behalf and are provided by the kernel itself. The library function <code>printf()</code> may look like a very general printing function, but all it really does is format the data into strings and write the string data using the low-level system call <code>write()</code>, which then sends the data to standard output.</p>
<p>Would you like to see what system calls are made by <code>printf()</code>? It&rsquo;s easy! Compile the following program:</p>
<pre><code>#include &lt;stdio.h&gt;
int main(void)
{ printf(&quot;hello&quot;); return 0; }
</code></pre>

<p>with <code>gcc -Wall -o hello hello.c</code>. Run the exectable with <code>strace ./hello</code>. Are you impressed? Every line you see corresponds to a system call. strace<sup id="fnref:3-1-1"><a class="footnote-ref" href="#fn:3-1-1" rel="footnote">4</a></sup> is a handy program that gives you details about what system calls a program is making, including which call is made, what its arguments are what it returns. It&rsquo;s an invaluable tool for figuring out things like what files a program is trying to access. Towards the end, you&rsquo;ll see a line which looks like <code>write(1, "hello", 5hello)</code>. There it is. The face behind the <code>printf()</code> mask. You may not be familiar with write, since most people use library functions for file I/O (like <code>fopen</code>, <code>fputs</code>, <code>fclose</code>). If that&rsquo;s the case, try looking at <code>man 2 write</code>. The 2nd man section is devoted to system calls (like <code>kill()</code> and <code>read()</code>. The 3rd man section is devoted to library calls, which you would probably be more familiar with (like <code>cosh()</code> and <code>random()</code>).</p>
<p>You can even write modules to replace the kernel&rsquo;s system calls, which we&rsquo;ll do shortly. Crackers often make use of this sort of thing for backdoors or trojans, but you can write your own modules to do more benign things, like have the kernel write Tee hee, that tickles! everytime someone tries to delete a file on your system.</p>
<h4 id="313-user-space-vs-kernel-space"><a name="user-content-313-user-space-vs-kernel-space" href="#313-user-space-vs-kernel-space" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.3. User Space vs Kernel Space</h4>
<p><strong>A kernel is all about access to resources</strong>, whether the resource in question happens to be a video card, a hard drive or even memory. Programs often compete for the same resource. As I just saved this document, updatedb started updating the locate database. My vim session and updatedb are both using the hard drive <strong>concurrently</strong>. The kernel needs to keep things orderly, and not give users access to resources whenever they feel like it. To this end, a can run in different modes. Each mode gives a different level of freedom to do what you want on the system. The Intel 80386 architecture has 4 of these modes, which are called rings. Unix uses only two rings; the highest ring (ring 0, also known as <code>supervisor mode</code> where everything is allowed to happen) and the lowest ring, which is called <code>user mode</code>.</p>
<p>Recall the discussion about <code>library functions</code> vs <code>system calls</code>. Typically, you use a library function in user mode. The library function calls one or more system calls, and these system calls execute on the library function&rsquo;s behalf, but do so in supervisor mode since they are part of the kernel itself. <strong>Once the system call completes its task, it returns and execution gets transfered back to user mode.</strong></p>
<h4 id="314-name-space"><a name="user-content-314-name-space" href="#314-name-space" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.4. Name Space</h4>
<p>When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you&rsquo;re writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples&rsquo; global variables; some of the variable names can clash. When a program has lots of global variables which aren&rsquo;t meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.</p>
<p><strong>When writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue.</strong> The best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols. By convention, all kernel prefixes are lowercase. If you don&rsquo;t want to declare everything as static, another option is to declare a <code>symbol table</code> and register it with a kernel. We&rsquo;ll get to this later.</p>
<p>The file <code>/proc/kallsyms</code> holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel&rsquo;s codespace.</p>
<h4 id="315-code-space"><a name="user-content-315-code-space" href="#315-code-space" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.5. Code space</h4>
<p><strong>Memory management</strong> is a very complicated subject&mdash;the majority of O&rsquo;Reilly&rsquo;s <code>Understanding The Linux Kernel</code> is just on memory management! We&rsquo;re not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.</p>
<p>If you haven&rsquo;t thought about what a <strong>segfault</strong> really means, you may be surprised to hear that pointers don&rsquo;t actually point to memory locations. Not real ones, anyway. When a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about<sup id="fnref:3-1-2"><a class="footnote-ref" href="#fn:3-1-2" rel="footnote">5</a></sup>. This memory begins with <code>0x00000000</code> and extends up to whatever it needs to be. Since the memory space for any two processes don&rsquo;t overlap, every process that can access a memory address, say <code>0xbffff978</code>, would be accessing a different location in real physical memory! The processes would be accessing an index named <code>0xbffff978</code> which points to some kind of offset into the region of memory set aside for that particular process. For the most part, a process like our <code>Hello, World</code> program can&rsquo;t access the space of another process, although there are ways which we&rsquo;ll talk about later.</p>
<p>The kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel&rsquo;s codespace rather than having its own. Therefore, if your module segfaults, the kernel segfaults. And if you start writing over data because of an off-by-one error, then you&rsquo;re trampling on kernel data (or code). This is even worse than it sounds, so try your best to be careful.</p>
<p>By the way, I would like to point out that the above discussion is true for any operating system which uses a <strong>monolithic kernel</strong><sup id="fnref:3-1-3"><a class="footnote-ref" href="#fn:3-1-3" rel="footnote">6</a></sup>. There are things called <strong>microkernels</strong> which have modules which get their own codespace. The <code>GNU Hurd</code> and <code>QNX Neutrino</code> are two examples of a microkernel.</p>
<h4 id="316-device-drivers"><a name="user-content-316-device-drivers" href="#316-device-drivers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.6. Device Drivers</h4>
<p>One class of module is the device driver, which provides functionality for hardware like a TV card or a serial port. On unix, each piece of hardware is represented by a file located in <code>/dev</code> named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the <code>es1370.o</code> sound card device driver might connect the <code>/dev/sound</code> device file to the Ensoniq IS1370 sound card. A userspace program like <code>mp3blaster</code> can use <code>/dev/sound</code> without ever knowing what kind of sound card is installed.</p>
<h5 id="3161-major-and-minor-numbers"><a name="user-content-3161-major-and-minor-numbers" href="#3161-major-and-minor-numbers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>3.1.6.1. Major and Minor Numbers</h5>
<p>Let&rsquo;s look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive:</p>
<pre><code># ls -l /dev/hda[1-3]
brw-rw----  1 root  disk  3, 1 Jul  5  2000 /dev/hda1
brw-rw----  1 root  disk  3, 2 Jul  5  2000 /dev/hda2
brw-rw----  1 root  disk  3, 3 Jul  5  2000 /dev/hda3
</code></pre>

<blockquote>
<p>Complement : if u use SATA, it may list sda# somehow.</p>
</blockquote>
<p>Notice the column of numbers separated by a comma? The first number is called the device&rsquo;s <code>major number</code>. The second number is the <code>minor number</code>. The major number tells you which driver is used to access the hardware. <strong>Each driver is assigned a unique major number; all device files with the same major number are controlled by the same driver.</strong> All the above major numbers are 3, because they&rsquo;re all controlled by the same driver.</p>
<p><strong>The minor number is used by the driver to distinguish between the various hardware it controls.</strong> Returning to the example above, although all three devices are handled by the same driver they have unique minor numbers because the driver sees them as being different pieces of hardware.</p>
<p>Devices are divided into two types: <strong>character devices</strong> and <strong>block devices</strong>. The difference is that block devices have a buffer for requests, so they can choose the best order in which to respond to the requests. This is important in the case of storage devices, where it&rsquo;s faster to read or write sectors which are close to each other, rather than those which are further apart. Another difference is that block devices can only accept input and return output in blocks (whose size can vary according to the device), whereas character devices are allowed to use as many or as few bytes as they like. Most devices in the world are character, because they don&rsquo;t need this type of buffering, and they don&rsquo;t operate with a fixed block size. You can tell whether a device file is for a block device or a character device by looking at the first character in the output of <code>ls -l</code>. If it&rsquo;s <code>b</code> then it&rsquo;s a block device, and if it&rsquo;s <code>c</code> then it&rsquo;s a character device. The devices you see above are block devices. Here are some character devices (the serial ports):</p>
<pre><code>crw-rw----  1 root  dial 4, 64 Feb 18 23:34 /dev/ttyS0
crw-r-----  1 root  dial 4, 65 Nov 17 10:26 /dev/ttyS1
crw-rw----  1 root  dial 4, 66 Jul  5  2000 /dev/ttyS2
crw-rw----  1 root  dial 4, 67 Jul  5  2000 /dev/ttyS3
</code></pre>

<p>If you want to see which major numbers have been assigned, you can look at <code>/usr/src/linux/Documentation/devices.txt</code>.</p>
<p>When the system was installed, all of those device files were created by the <code>mknod</code> command. To create a new char device named <code>coffee</code> with major/minor number 12 and 2, simply do <code>mknod /dev/coffee c 12 2</code>. You don&rsquo;t have to put your device files into<code>/dev</code>, but it&rsquo;s done by convention. Linus put his device files in <code>/dev</code>, and so should you. However, when creating a device file for testing purposes, it&rsquo;s probably OK to place it in your working directory where you compile the kernel module. Just be sure to put it in the right place when you&rsquo;re done writing the device driver.</p>
<p>I would like to make a few last points which are implicit from the above discussion, but I&rsquo;d like to make them explicit just in case. <strong>When a device file is accessed, the kernel uses the major number of the file to determine which driver should be used to handle the access.</strong> This means that the kernel doesn&rsquo;t really need to use or even know about the minor number. The driver itself is the only thing that cares about the minor number. It uses the minor number to distinguish between different pieces of hardware.</p>
<p>By the way, when I say <code>hardware</code>, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files:</p>
<pre><code>% ls -l /dev/fd0 /dev/fd0u1680
brwxrwxrwx   1 root  floppy   2,  0 Jul  5  2000 /dev/fd0
brw-rw----   1 root  floppy   2, 44 Jul  5  2000 /dev/fd0u1680
</code></pre>

<p>By now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 2). You might even be aware that these both represent your floppy drive, even if you only have one floppy drive. Why two files? One represents the floppy drive with 1.44 of storage. The other is the same floppy drive with 1.68 of storage, and corresponds to what some people call a <code>superformatted</code> disk. One that holds more data than a standard formatted floppy. So here&rsquo;s a case where two device files with different minor number actually represent the same piece of physical hardware. So just be aware that the word <code>hardware</code> in our discussion can mean something very abstract.</p>
<h2 id="chapter-4-character-device-files"><a name="user-content-chapter-4-character-device-files" href="#chapter-4-character-device-files" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 4. Character Device Files</h2>
<h3 id="41-character-device-drivers"><a name="user-content-41-character-device-drivers" href="#41-character-device-drivers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1. Character Device Drivers</h3>
<h4 id="411-the-file_operations-structure"><a name="user-content-411-the-file_operations-structure" href="#411-the-file_operations-structure" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.1. The file_operations Structure</h4>
<p>The <code>file_operations</code> structure is defined in <code>linux/fs.h</code>, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.</p>
<p>For example, every character driver needs to define a function that reads from the device. The <code>file_operations</code> structure holds the address of the module&rsquo;s function that performs that operation. Here is what the definition looks like for kernel 2.6.5:</p>
<pre><code>struct file_operations {
    struct module *owner;
     loff_t(*llseek) (struct file *, loff_t, int);
     ssize_t(*read) (struct file *, char __user *, size_t, loff_t *);
     ssize_t(*aio_read) (struct kiocb *, char __user *, size_t, loff_t);
     ssize_t(*write) (struct file *, const char __user *, size_t, loff_t *);
     ssize_t(*aio_write) (struct kiocb *, const char __user *, size_t,
                  loff_t);
    int (*readdir) (struct file *, void *, filldir_t);
    unsigned int (*poll) (struct file *, struct poll_table_struct *);
    int (*ioctl) (struct inode *, struct file *, unsigned int,
              unsigned long);
    int (*mmap) (struct file *, struct vm_area_struct *);
    int (*open) (struct inode *, struct file *);
    int (*flush) (struct file *);
    int (*release) (struct inode *, struct file *);
    int (*fsync) (struct file *, struct dentry *, int datasync);
    int (*aio_fsync) (struct kiocb *, int datasync);
    int (*fasync) (int, struct file *, int);
    int (*lock) (struct file *, int, struct file_lock *);
     ssize_t(*readv) (struct file *, const struct iovec *, unsigned long,
              loff_t *);
     ssize_t(*writev) (struct file *, const struct iovec *, unsigned long,
               loff_t *);
     ssize_t(*sendfile) (struct file *, loff_t *, size_t, read_actor_t,
                 void __user *);
     ssize_t(*sendpage) (struct file *, struct page *, int, size_t,
                 loff_t *, int);
    unsigned long (*get_unmapped_area) (struct file *, unsigned long,
                        unsigned long, unsigned long,
                        unsigned long);
};
</code></pre>

<p>Some operations are not implemented by a driver. For example, a driver that handles a video card won&rsquo;t need to read from a directory structure. The corresponding entries in the <code>file_operations</code> structure should be set to <code>NULL</code>.</p>
<p>There is a gcc extension that makes assigning to this structure more convenient. You&rsquo;ll see it in modern drivers, and may catch you by surprise. This is what the new way of assigning to the structure looks like:</p>
<pre><code>struct file_operations fops = {
    read: device_read,
    write: device_write,
    open: device_open,
    release: device_release
};
</code></pre>

<p>However, there&rsquo;s also a <strong>C99</strong> way of assigning to elements of a structure, and this is definitely preferred over using the GNU extension. The version of gcc the author used when writing this, 2.95, supports the new <strong>C99</strong> syntax. <strong>You should use this syntax in case someone wants to port your driver. It will help with compatibility</strong>:</p>
<pre><code>struct file_operations fops = {
    .read = device_read,
    .write = device_write,
    .open = device_open,
    .release = device_release
};
</code></pre>

<p>The meaning is clear, and you should be aware that any member of the structure which you don&rsquo;t explicitly assign will be initialized to <code>NULL</code> by gcc.</p>
<p>An instance of struct <code>file_operations</code> containing pointers to functions that are used to implement <code>read</code>, <code>write</code>, <code>open</code>, &hellip; <code>syscalls</code> is commonly named fops.</p>
<h4 id="412-the-structure"><a name="user-content-412-the-structure" href="#412-the-structure" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.2. The structure</h4>
<p>Each device is represented in the kernel by a structure, which is defined in <code>linux/fs.h</code>. Be aware that a is a kernel level structure and never appears in a user space program. It&rsquo;s not the same thing as a , which is defined by glibc and would never appear in a kernel space function. Also, its name is a bit misleading; it represents an abstract open <code>file</code>, not a file on a disk, which is represented by a structure named <code>inode</code>.</p>
<p>An instance of <code>struct file</code> is commonly named <code>filp</code>. You&rsquo;ll also see it refered to as <code>struct file file</code>. Resist the temptation.</p>
<p>Go ahead and look at the definition of file. Most of the entries you see, like struct <code>dentry</code> aren&rsquo;t used by device drivers, and you can ignore them. This is because drivers don&rsquo;t fill file directly; they only use structures contained in file which are created elsewhere.</p>
<h4 id="413-registering-a-device"><a name="user-content-413-registering-a-device" href="#413-registering-a-device" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.3. Registering A Device</h4>
<p>As discussed earlier, char devices are accessed through device files, usually located in <code>/dev</code><sup id="fnref:4-1-1"><a class="footnote-ref" href="#fn:4-1-1" rel="footnote">7</a></sup>. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it&rsquo;s operating on, just in case the driver handles more than one device.</p>
<p>Adding a driver to your system means registering it with the kernel. This is synonymous with assigning it a major number during the module&rsquo;s initialization. You do this by using the <code>register_chrdev</code> function, defined by <code>linux/fs.h</code>.</p>
<pre><code>int register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
</code></pre>

<p>where <code>unsigned int major</code> is the major number you want to request, <code>const char *name</code> is the name of the device as it&rsquo;ll appear in <code>/proc/devices</code> and <code>struct file_operations *fops</code> is a pointer to the <code>file_operations table</code> for your driver. A <strong>negative return value</strong> means the registration failed. Note that we didn&rsquo;t pass the minor number to <code>register_chrdev</code>. <strong>That&rsquo;s because the kernel doesn&rsquo;t care about the minor number; only our driver uses it.</strong></p>
<p>Now the question is, how do you get a major number without hijacking one that&rsquo;s already in use? The easiest way would be to look through <code>Documentation/devices.txt</code> and pick an unused one. That&rsquo;s a bad way of doing things because you&rsquo;ll never be sure if the number you picked will be assigned later. <strong>The answer is that you can ask the kernel to assign you a dynamic major number.</strong></p>
<p>If you pass a <code>major number</code> of 0 to <code>register_chrdev</code>, the return value will be the dynamically allocated major number. The downside is that you can&rsquo;t make a device file in advance, since you don&rsquo;t know what the major number will be. There are a couple of ways to do this. First, the driver itself can print the newly assigned number and we can make the device file by hand. Second, the newly registered device will have an entry in <code>/proc/devices</code>, and we can either make the device file by hand or write a shell script to read the file in and make the device file. The third method is we can have our driver make the device file using the mknod system call after a successful registration and rm during the call to <code>cleanup_module</code>.</p>
<h4 id="414-unregistering-a-device"><a name="user-content-414-unregistering-a-device" href="#414-unregistering-a-device" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.4. Unregistering A Device</h4>
<p>We can&rsquo;t allow the kernel module to be rmmod&rsquo;ed whenever root feels like it. If the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be. If we&rsquo;re lucky, no other code was loaded there, and we&rsquo;ll get an ugly error message. If we&rsquo;re unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel. The results of this would be impossible to predict, but they can&rsquo;t be very positive.</p>
<p>Normally, when you don&rsquo;t want to allow something, you return an error code (a negative number) from the function which is supposed to do it. With <code>cleanup_module</code> that&rsquo;s impossible because it&rsquo;s a void function. <strong>However, there&rsquo;s a counter which keeps track of how many processes are using your module.</strong> You can see what it&rsquo;s value is by looking at the 3rd field of <code>/proc/modules</code>. If this number isn&rsquo;t zero, rmmod will fail. Note that you don&rsquo;t have to check the counter from within <code>cleanup_module</code> because the check will be performed for you by the system call <code>sys_delete_module</code>, defined in <code>linux/module.c</code>. You shouldn&rsquo;t use this counter directly, but there are functions defined in <code>linux/module.h</code> which let you increase, decrease and display this counter:</p>
<ul>
<li>try_module_get(THIS_MODULE): Increment the use count.</li>
<li>module_put(THIS_MODULE): Decrement the use count.</li>
</ul>
<p>It&rsquo;s important to keep the counter accurate; if you ever do lose track of the correct usage count, you&rsquo;ll never be able to unload the module; it&rsquo;s now reboot time, boys and girls. This is bound to happen to you sooner or later during a module&rsquo;s development.</p>
<h4 id="415-chardevc"><a name="user-content-415-chardevc" href="#415-chardevc" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.5. chardev.c</h4>
<p>The next code sample creates a char driver named chardev. You can cat its device file (or open the file with a program) and the driver will put the number of times the device file has been read from into the file. We don&rsquo;t support writing to the file (like <code>echo "hi" &gt; /dev/hello</code>), but catch these attempts and tell the user that the operation isn&rsquo;t supported. Don&rsquo;t worry if you don&rsquo;t see what we do with the data we read into the buffer; we don&rsquo;t do much with it. We simply read in the data and print a message acknowledging that we received it.</p>
<p>Example 4-1. chardev.c</p>
<pre><code>/*
 *  chardev.c: Creates a read-only char device that says how many times
 *  you've read from the dev file
 */

#include &lt;linux/kernel.h&gt;
#include &lt;linux/module.h&gt;
#include &lt;linux/fs.h&gt;
#include &lt;asm/uaccess.h&gt;    /* for put_user */

/*  
 *  Prototypes - this would normally go in a .h file
 */
int init_module(void);
void cleanup_module(void);
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);

#define SUCCESS 0
#define DEVICE_NAME &quot;chardev&quot;   /* Dev name as it appears in /proc/devices   */
#define BUF_LEN 80      /* Max length of the message from the device */

/* 
 * Global variables are declared as static, so are global within the file. 
 */

static int Major;       /* Major number assigned to our device driver */
static int Device_Open = 0; /* Is device open?  
                 * Used to prevent multiple access to device */
static char msg[BUF_LEN];   /* The msg the device will give when asked */
static char *msg_Ptr;

static struct file_operations fops = {
    .read = device_read,
    .write = device_write,
    .open = device_open,
    .release = device_release
};

/*
 * This function is called when the module is loaded
 */
int init_module(void)
{
        Major = register_chrdev(0, DEVICE_NAME, &amp;fops);

    if (Major &lt; 0) {
      printk(KERN_ALERT &quot;Registering char device failed with %d\n&quot;, Major);
      return Major;
    }

    printk(KERN_INFO &quot;I was assigned major number %d. To talk to\n&quot;, Major);
    printk(KERN_INFO &quot;the driver, create a dev file with\n&quot;);
    printk(KERN_INFO &quot;'mknod /dev/%s c %d 0'.\n&quot;, DEVICE_NAME, Major);
    printk(KERN_INFO &quot;Try various minor numbers. Try to cat and echo to\n&quot;);
    printk(KERN_INFO &quot;the device file.\n&quot;);
    printk(KERN_INFO &quot;Remove the device file and module when done.\n&quot;);

    return SUCCESS;
}

/*
 * This function is called when the module is unloaded
 */
void cleanup_module(void)
{
    /* 
     * Unregister the device 
     */
    int ret = unregister_chrdev(Major, DEVICE_NAME);
    if (ret &lt; 0)
        printk(KERN_ALERT &quot;Error in unregister_chrdev: %d\n&quot;, ret);
}

/*
 * Methods
 */

/* 
 * Called when a process tries to open the device file, like
 * &quot;cat /dev/mycharfile&quot;
 */
static int device_open(struct inode *inode, struct file *file)
{
    static int counter = 0;

    if (Device_Open)
        return -EBUSY;

    Device_Open++;
    sprintf(msg, &quot;I already told you %d times Hello world!\n&quot;, counter++);
    msg_Ptr = msg;
    try_module_get(THIS_MODULE);

    return SUCCESS;
}

/* 
 * Called when a process closes the device file.
 */
static int device_release(struct inode *inode, struct file *file)
{
    Device_Open--;      /* We're now ready for our next caller */

    /* 
     * Decrement the usage count, or else once you opened the file, you'll
     * never get get rid of the module. 
     */
    module_put(THIS_MODULE);

    return 0;
}

/* 
 * Called when a process, which already opened the dev file, attempts to
 * read from it.
 */
static ssize_t device_read(struct file *filp,   /* see include/linux/fs.h   */
               char *buffer,    /* buffer to fill with data */
               size_t length,   /* length of the buffer     */
               loff_t * offset)
{
    /*
     * Number of bytes actually written to the buffer 
     */
    int bytes_read = 0;

    /*
     * If we're at the end of the message, 
     * return 0 signifying end of file 
     */
    if (*msg_Ptr == 0)
        return 0;

    /* 
     * Actually put the data into the buffer 
     */
    while (length &amp;&amp; *msg_Ptr) {

        /* 
         * The buffer is in the user data segment, not the kernel 
         * segment so &quot;*&quot; assignment won't work.  We have to use 
         * put_user which copies data from the kernel data segment to
         * the user data segment. 
         */
        put_user(*(msg_Ptr++), buffer++);

        length--;
        bytes_read++;
    }

    /* 
     * Most read functions return the number of bytes put into the buffer
     */
    return bytes_read;
}

/*  
 * Called when a process writes to dev file: echo &quot;hi&quot; &gt; /dev/hello 
 */
static ssize_t
device_write(struct file *filp, const char *buff, size_t len, loff_t * off)
{
    printk(KERN_ALERT &quot;Sorry, this operation isn't supported.\n&quot;);
    return -EINVAL;
}
</code></pre>

<h4 id="416-writing-modules-for-multiple-kernel-versions"><a name="user-content-416-writing-modules-for-multiple-kernel-versions" href="#416-writing-modules-for-multiple-kernel-versions" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>4.1.6. Writing Modules for Multiple Kernel Versions</h4>
<p>The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility &ndash; a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.</p>
<p>The Linux kernel versions are divided between the stable versions (n.<code>$&lt;$even number$&gt;$.m</code>) and the development versions (n.<code>$&lt;$odd number$&gt;$.m</code>). The development versions include all the cool new ideas, including those which will be considered a mistake, or reimplemented, in the next version. As a result, you can&rsquo;t trust the interface to remain the same in those versions (which is why I don&rsquo;t bother to support them in this book, it&rsquo;s too much work and it would become dated too quickly). In the stable versions, on the other hand, we can expect the interface to remain the same regardless of the bug fix version (the m number).</p>
<p>There are differences between different kernel versions, and if you want to support multiple kernel versions, you&rsquo;ll find yourself having to code conditional compilation directives. The way to do this to compare the macro <code>LINUX_VERSION_CODE</code> to the macro <code>KERNEL_VERSION</code>. In version a.b.c of the kernel, the value of this macro would be <code>$2^{16}a+2^{8}b+c$</code>.</p>
<p>While previous versions of this guide showed how you can write backward compatible code with such constructs in great detail, we decided to break with this tradition for the better. People interested in doing such might now use a LKMPG with a version matching to their kernel. We decided to version the LKMPG like the kernel, at least as far as major and minor number are concerned. We use the patchlevel for our own versioning so use LKMPG version 2.4.x for kernels 2.4.x, use LKMPG version 2.6.x for kernels 2.6.x and so on. Also make sure that you always use current, up to date versions of both, kernel and guide.</p>
<p>Update: What we&rsquo;ve said above was true for kernels up to and including 2.6.10. You might already have noticed that recent kernels look different. In case you haven&rsquo;t they look like 2.6.x.y now. The meaning of the first three items basically stays the same, but a subpatchlevel has been added and will indicate security fixes till the next stable patchlevel is out. So people can choose between a stable tree with security updates and use the latest kernel as developer tree. Search the kernel mailing list archives  if you&rsquo;re interested in the full story.</p>
<h2 id="chapter-5-the-proc-file-system"><a name="user-content-chapter-5-the-proc-file-system" href="#chapter-5-the-proc-file-system" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 5. The /proc File System</h2>
<h3 id="51-the-proc-file-system"><a name="user-content-51-the-proc-file-system" href="#51-the-proc-file-system" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>5.1. The /proc File System</h3>
<blockquote>
<p>Recommend reading <a href="http://www.ibm.com/developerworks/linux/library/l-proc/index.html">Access the Linux kernel using the /proc filesystem</a> firstly.</p>
</blockquote>
<p>In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes &mdash; the <code>/proc</code> file system. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as <code>/proc/modules</code> which provides the list of modules and <code>/proc/meminfo</code> which stats memory usage statistics.</p>
<p>The method to use the proc file system is very similar to the one used with device drivers &mdash; a structure is created with all the information needed for the <code>/proc</code> file, including pointers to any handler functions (in our case there is only one, the one called when somebody attempts to read from the <code>/proc</code> file). Then, <code>init_module</code> registers the structure with the kernel and <code>cleanup_module</code> unregisters it.</p>
<p>The reason we use <code>proc_register_dynamic</code><sup id="fnref:5-1-1"><a class="footnote-ref" href="#fn:5-1-1" rel="footnote">8</a></sup> is because we don&rsquo;t want to determine the <code>inode number</code> used for our file in advance, but to allow the kernel to determine it to prevent clashes. Normal file systems are located on a disk, rather than just in memory (which is where <code>/proc</code> is), and in that case the <code>inode number</code> is a pointer to a disk location where the file&rsquo;s index-node (inode for short) is located. The inode contains information about the file, for example the file&rsquo;s permissions, together with a pointer to the disk location or locations where the file&rsquo;s data can be found.</p>
<p>Because we don&rsquo;t get called when the file is opened or closed, there&rsquo;s nowhere for us to put <code>try_module_get</code> and <code>try_module_put</code> in this module, and if the file is opened and then the module is removed, there&rsquo;s no way to avoid the consequences.</p>
<p>Here a simple example showing how to use a <code>/proc</code> file. This is the <code>HelloWorld</code> for the <code>/proc</code> filesystem. There are three parts: </p>
<ol>
<li><strong>create</strong> the file <code>/proc/helloworld</code> in the function <code>init_module</code>, </li>
<li>return a value (and a buffer) when the file <code>/proc/helloworld</code> is <strong>read</strong> in the callback function <code>procfs_read</code>, and </li>
<li><strong>delete</strong> the file <code>/proc/helloworld</code> in the function <code>cleanup_module</code>.</li>
</ol>
<p>The <code>/proc/helloworld</code> is created when the module is loaded with the function <code>create_proc_entry</code>. The return value is a <code>struct proc_dir_entry *</code>, and it will be used to configure the file <code>/proc/helloworld</code> (for example, the owner of this file). A null return value means that the creation has failed.</p>
<p>Each time, everytime the file <code>/proc/helloworld</code> is read, the function <code>procfs_read</code> is called. Two parameters of this function are very important: the <strong>buffer</strong> (the first parameter) and the <strong>offset</strong> (the third one). The content of the buffer will be returned to the application which read it (for example the cat command). The offset is the current position in the file. If the return value of the function isn&rsquo;t null, then this function is called again. So be careful with this function, if it never returns zero, the read function is called endlessly.</p>
<pre><code>% cat /proc/helloworld
HelloWorld!
</code></pre>

<p>Example 5-1. procfs1.c</p>
<pre><code>/*
 *  procfs1.c -  create a &quot;file&quot; in /proc
 *
 */

#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use the proc fs */

#define procfs_name &quot;helloworld&quot;

/**
 * This structure hold information about the /proc file
 *
 */
struct proc_dir_entry *Our_Proc_File;

/* Put data into the proc fs file.
 * 
 * Arguments
 * =========
 * 1. The buffer where the data is to be inserted, if
 *    you decide to use it.
 * 2. A pointer to a pointer to characters. This is
 *    useful if you don't want to use the buffer
 *    allocated by the kernel.
 * 3. The current position in the file
 * 4. The size of the buffer in the first argument.
 * 5. Write a &quot;1&quot; here to indicate EOF.
 * 6. A pointer to data (useful in case one common 
 *    read for multiple /proc/... entries)
 *
 * Usage and Return Value
 * ======================
 * A return value of zero means you have no further
 * information at this time (end of file). A negative
 * return value is an error condition.
 *
 * For More Information
 * ====================
 * The way I discovered what to do with this function
 * wasn't by reading documentation, but by reading the
 * code which used it. I just looked to see what uses
 * the get_info field of proc_dir_entry struct (I used a
 * combination of find and grep, if you're interested),
 * and I saw that  it is used in &lt;kernel source
 * directory&gt;/fs/proc/array.c.
 *
 * If something is unknown about the kernel, this is
 * usually the way to go. In Linux we have the great
 * advantage of having the kernel source code for
 * free - use it.
 */
int
procfile_read(char *buffer,
          char **buffer_location,
          off_t offset, int buffer_length, int *eof, void *data)
{
    int ret;

    printk(KERN_INFO &quot;procfile_read (/proc/%s) called\n&quot;, procfs_name);

    /* 
     * We give all of our information in one go, so if the
     * user asks us if we have more information the
     * answer should always be no.
     *
     * This is important because the standard read
     * function from the library would continue to issue
     * the read system call until the kernel replies
     * that it has no more information, or until its
     * buffer is filled.
     */
    if (offset &gt; 0) {
        /* we have finished to read, return 0 */
        ret  = 0;
    } else {
        /* fill the buffer, return the buffer size */
        ret = sprintf(buffer, &quot;HelloWorld!\n&quot;);
    }

    return ret;
}

int init_module()
{
    Our_Proc_File = create_proc_entry(procfs_name, 0644, NULL);

    if (Our_Proc_File == NULL) {
        remove_proc_entry(procfs_name, &amp;proc_root);
        printk(KERN_ALERT &quot;Error: Could not initialize /proc/%s\n&quot;,
               procfs_name);
        return -ENOMEM;
    }

    Our_Proc_File-&gt;read_proc = procfile_read;
    Our_Proc_File-&gt;owner     = THIS_MODULE;
    Our_Proc_File-&gt;mode      = S_IFREG | S_IRUGO;
    Our_Proc_File-&gt;uid   = 0;
    Our_Proc_File-&gt;gid   = 0;
    Our_Proc_File-&gt;size      = 37;

    printk(KERN_INFO &quot;/proc/%s created\n&quot;, procfs_name);    
    return 0;   /* everything is ok */
}

void cleanup_module()
{
    remove_proc_entry(procfs_name, &amp;proc_root);
    printk(KERN_INFO &quot;/proc/%s removed\n&quot;, procfs_name);
}
</code></pre>

<h3 id="52-read-and-write-a-proc-file"><a name="user-content-52-read-and-write-a-proc-file" href="#52-read-and-write-a-proc-file" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>5.2. Read and Write a /proc File</h3>
<p>We have seen a very simple example for a <code>/proc</code> file where we only read the file <code>/proc/helloworld</code>. It&rsquo;s also possible to write in a <code>/proc</code> file. It works the same way as read, a function is called when the <code>/proc</code> file is written. But there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with <code>copy_from_user</code> or <code>get_user</code>)</p>
<p>The reason for <code>copy_from_user</code> or <code>get_user</code> is that Linux memory (on Intel architecture, it may be different under some other processors) is segmented. This means that a pointer, by itself, does not reference a unique location in memory, only a location in a memory segment, and you need to know which memory segment it is to be able to use it. There is one memory segment for the kernel, and one for each of the processes.</p>
<p>The only memory segment accessible to a process is its own, so when writing regular programs to run as processes, there&rsquo;s no need to worry about segments. When you write a kernel module, normally you want to access the kernel memory segment, which is handled automatically by the system. However, when the content of a memory buffer needs to be passed between the currently running process and the kernel, the kernel function receives a pointer to the memory buffer which is in the process segment. The put_user and <code>get_user</code> macros allow you to access that memory. These functions handle only one caracter, you can handle several caracters with copy_to_user and <code>copy_from_user</code>. As the buffer (in read or write function) is in kernel space, for write function you need to import data because  it comes from user space, but not for the read function because data is already in kernel space.</p>
<p>Example 5-2. procfs2.c<br />
<pre><code>/**
 *  procfs2.c -  create a &quot;file&quot; in /proc
 *
 */

#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use the proc fs */
#include &lt;asm/uaccess.h&gt;    /* for copy_from_user */

#define PROCFS_MAX_SIZE     1024
#define PROCFS_NAME         &quot;buffer1k&quot;

/**
 * This structure hold information about the /proc file
 *
 */
static struct proc_dir_entry *Our_Proc_File;

/**
 * The buffer used to store character for this module
 *
 */
static char procfs_buffer[PROCFS_MAX_SIZE];

/**
 * The size of the buffer
 *
 */
static unsigned long procfs_buffer_size = 0;

/** 
 * This function is called then the /proc file is read
 *
 */
int 
procfile_read(char *buffer,
          char **buffer_location,
          off_t offset, int buffer_length, int *eof, void *data)
{
    int ret;

    printk(KERN_INFO &quot;procfile_read (/proc/%s) called\n&quot;, PROCFS_NAME);

    if (offset &gt; 0) {
        /* we have finished to read, return 0 */
        ret  = 0;
    } else {
        /* fill the buffer, return the buffer size */
        memcpy(buffer, procfs_buffer, procfs_buffer_size);
        ret = procfs_buffer_size;
    }

    return ret;
}

/**
 * This function is called with the /proc file is written
 *
 */
int procfile_write(struct file *file, const char *buffer, unsigned long count,
           void *data)
{
    /* get buffer size */
    procfs_buffer_size = count;
    if (procfs_buffer_size &gt; PROCFS_MAX_SIZE ) {
        procfs_buffer_size = PROCFS_MAX_SIZE;
    }

    /* write data to the buffer */
    if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {
        return -EFAULT;
    }

    return procfs_buffer_size;
}

/**
 *This function is called when the module is loaded
 *
 */
int init_module()
{
    /* create the /proc file */
    Our_Proc_File = create_proc_entry(PROCFS_NAME, 0644, NULL);

    if (Our_Proc_File == NULL) {
        remove_proc_entry(PROCFS_NAME, &amp;proc_root);
        printk(KERN_ALERT &quot;Error: Could not initialize /proc/%s\n&quot;,
            PROCFS_NAME);
        return -ENOMEM;
    }

    Our_Proc_File-&gt;read_proc  = procfile_read;
    Our_Proc_File-&gt;write_proc = procfile_write;
    Our_Proc_File-&gt;owner      = THIS_MODULE;
    Our_Proc_File-&gt;mode       = S_IFREG | S_IRUGO;
    Our_Proc_File-&gt;uid    = 0;
    Our_Proc_File-&gt;gid    = 0;
    Our_Proc_File-&gt;size       = 37;

    printk(KERN_INFO &quot;/proc/%s created\n&quot;, PROCFS_NAME);    
    return 0;   /* everything is ok */
}

/**
 *This function is called when the module is unloaded
 *
 */
void cleanup_module()
{
    remove_proc_entry(PROCFS_NAME, &amp;proc_root);
    printk(KERN_INFO &quot;/proc/%s removed\n&quot;, PROCFS_NAME);
}
</code></pre></p>
<h3 id="53-manage-proc-file-with-standard-filesystem"><a name="user-content-53-manage-proc-file-with-standard-filesystem" href="#53-manage-proc-file-with-standard-filesystem" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>5.3. Manage /proc file with standard filesystem</h3>
<p>We have seen how to read and write a <code>/proc</code> file with the <code>/proc</code> interface. But it&rsquo;s also possible to manage <code>/proc</code> file with inodes. The main interest is to use advanced function, like permissions.</p>
<p>In Linux, there is a standard mechanism for file system registration. Since every file system has to have its own functions to handle inode and file operations<sup id="fnref:5-3-1"><a class="footnote-ref" href="#fn:5-3-1" rel="footnote">9</a></sup>, there is a special structure to hold pointers to all those functions, <code>struct inode_operations</code>, which includes a pointer to <code>struct file_operations</code>. In <code>/proc</code>, whenever we register a new file, we&rsquo;re allowed to specify which struct inode_operations will be used to access to it. This is the mechanism we use, a <code>struct inode_operations</code> which includes a pointer to a <code>struct file_operations</code> which includes pointers to our <code>procfs_read</code> and <code>procfs_write</code> functions.</p>
<p>Another interesting point here is the <code>module_permission</code> function. This function is called whenever a process tries to do something with the <code>/proc</code> file, and it can decide whether to allow access or not. Right now it is only based on the operation and the uid of the current user (as available in current, a pointer to a structure which includes information on the currently running process), but it could be based on anything we like, such as what other processes are doing with the same file, the time of day, or the last input we received.</p>
<p>It&rsquo;s important to note that the standard roles of read and write are reversed in the kernel. Read functions are used for output, whereas write functions are used for input. The reason for that is that read and write refer to the user&rsquo;s point of view &mdash; if a process reads something from the kernel, then the kernel needs to output it, and if a process writes something to the kernel, then the kernel receives it as input.</p>
<p>Example 5-3. procfs3.c</p>
<pre><code>/* 
 *  procfs3.c -  create a &quot;file&quot; in /proc, use the file_operation way
 *          to manage the file.
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use proc fs */
#include &lt;asm/uaccess.h&gt;    /* for copy_*_user */

#define PROC_ENTRY_FILENAME     &quot;buffer2k&quot;
#define PROCFS_MAX_SIZE     2048

/**
 * The buffer (2k) for this module
 *
 */
static char procfs_buffer[PROCFS_MAX_SIZE];

/**
 * The size of the data hold in the buffer
 *
 */
static unsigned long procfs_buffer_size = 0;

/**
 * The structure keeping information about the /proc file
 *
 */
static struct proc_dir_entry *Our_Proc_File;

/**
 * This funtion is called when the /proc file is read
 *
 */
static ssize_t procfs_read(struct file *filp,   /* see include/linux/fs.h   */
                 char *buffer,  /* buffer to fill with data */
                 size_t length, /* length of the buffer     */
                 loff_t * offset)
{
    static int finished = 0;

    /* 
     * We return 0 to indicate end of file, that we have
     * no more information. Otherwise, processes will
     * continue to read from us in an endless loop. 
     */
    if ( finished ) {
        printk(KERN_INFO &quot;procfs_read: END\n&quot;);
        finished = 0;
        return 0;
    }

    finished = 1;

    /* 
     * We use put_to_user to copy the string from the kernel's
     * memory segment to the memory segment of the process
     * that called us. get_from_user, BTW, is
     * used for the reverse. 
     */
    if ( copy_to_user(buffer, procfs_buffer, procfs_buffer_size) ) {
        return -EFAULT;
    }

    printk(KERN_INFO &quot;procfs_read: read %lu bytes\n&quot;, procfs_buffer_size);

    return procfs_buffer_size;  /* Return the number of bytes &quot;read&quot; */
}

/*
 * This function is called when /proc is written
 */
static ssize_t
procfs_write(struct file *file, const char *buffer, size_t len, loff_t * off)
{
    if ( len &gt; PROCFS_MAX_SIZE )    {
        procfs_buffer_size = PROCFS_MAX_SIZE;
    }
    else    {
        procfs_buffer_size = len;
    }

    if ( copy_from_user(procfs_buffer, buffer, procfs_buffer_size) ) {
        return -EFAULT;
    }

    printk(KERN_INFO &quot;procfs_write: write %lu bytes\n&quot;, procfs_buffer_size);

    return procfs_buffer_size;
}

/* 
 * This function decides whether to allow an operation
 * (return zero) or not allow it (return a non-zero
 * which indicates why it is not allowed).
 *
 * The operation can be one of the following values:
 * 0 - Execute (run the &quot;file&quot; - meaningless in our case)
 * 2 - Write (input to the kernel module)
 * 4 - Read (output from the kernel module)
 *
 * This is the real function that checks file
 * permissions. The permissions returned by ls -l are
 * for referece only, and can be overridden here.
 */

static int module_permission(struct inode *inode, int op, struct nameidata *foo)
{
    /* 
     * We allow everybody to read from our module, but
     * only root (uid 0) may write to it 
     */
    if (op == 4 || (op == 2 &amp;&amp; current-&gt;euid == 0))
        return 0;

    /* 
     * If it's anything else, access is denied 
     */
    return -EACCES;
}

/* 
 * The file is opened - we don't really care about
 * that, but it does mean we need to increment the
 * module's reference count. 
 */
int procfs_open(struct inode *inode, struct file *file)
{
    try_module_get(THIS_MODULE);
    return 0;
}

/* 
 * The file is closed - again, interesting only because
 * of the reference count. 
 */
int procfs_close(struct inode *inode, struct file *file)
{
    module_put(THIS_MODULE);
    return 0;       /* success */
}

static struct file_operations File_Ops_4_Our_Proc_File = {
    .read    = procfs_read,
    .write   = procfs_write,
    .open    = procfs_open,
    .release = procfs_close,
};

/* 
 * Inode operations for our proc file. We need it so
 * we'll have some place to specify the file operations
 * structure we want to use, and the function we use for
 * permissions. It's also possible to specify functions
 * to be called for anything else which could be done to
 * an inode (although we don't bother, we just put
 * NULL). 
 */

static struct inode_operations Inode_Ops_4_Our_Proc_File = {
    .permission = module_permission,    /* check for permissions */
};

/* 
 * Module initialization and cleanup 
 */
int init_module()
{
    /* create the /proc file */
    Our_Proc_File = create_proc_entry(PROC_ENTRY_FILENAME, 0644, NULL);

    /* check if the /proc file was created successfuly */
    if (Our_Proc_File == NULL){
        printk(KERN_ALERT &quot;Error: Could not initialize /proc/%s\n&quot;,
               PROC_ENTRY_FILENAME);
        return -ENOMEM;
    }

    Our_Proc_File-&gt;owner = THIS_MODULE;
    Our_Proc_File-&gt;proc_iops = &amp;Inode_Ops_4_Our_Proc_File;
    Our_Proc_File-&gt;proc_fops = &amp;File_Ops_4_Our_Proc_File;
    Our_Proc_File-&gt;mode = S_IFREG | S_IRUGO | S_IWUSR;
    Our_Proc_File-&gt;uid = 0;
    Our_Proc_File-&gt;gid = 0;
    Our_Proc_File-&gt;size = 80;

    printk(KERN_INFO &quot;/proc/%s created\n&quot;, PROC_ENTRY_FILENAME);

    return 0;   /* success */
}

void cleanup_module()
{
    remove_proc_entry(PROC_ENTRY_FILENAME, &amp;proc_root);
    printk(KERN_INFO &quot;/proc/%s removed\n&quot;, PROC_ENTRY_FILENAME);
}
</code></pre>

<p>Still hungry for procfs examples? Well, first of all keep in mind, there are rumors around, claiming that procfs is on it&rsquo;s way out, consider using sysfs instead. Second, if you really can&rsquo;t get enough, there&rsquo;s a highly recommendable bonus level for procfs below <code>linux/Documentation/DocBook/</code>. Use make help in your toplevel kernel directory for instructions about how to convert it into your favourite format. Example: make htmldocs . Consider using this mechanism, in case you want to document something kernel related yourself.</p>
<h3 id="54-manage-proc-file-with-seq_file"><a name="user-content-54-manage-proc-file-with-seq_file" href="#54-manage-proc-file-with-seq_file" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>5.4. Manage /proc file with seq_file</h3>
<p>As we have seen, writing a <code>/proc</code> file may be quite &ldquo;complex&rdquo;. So to help people writting <code>/proc</code> file, there is an API named seq_file that helps formating a <code>/proc</code> file for output. It&rsquo;s based on sequence, which is composed of 3 functions: <code>start()</code>, <code>next()</code>, and <code>stop()</code>. The seq_file API starts a sequence when a user read the <code>/proc</code> file.</p>
<p>A sequence begins with the call of the function <code>start()</code>. If the return is a non <code>NULL</code> value, the function <code>next()</code> is called. This function is an iterator, the goal is to go thought all the data. Each time <code>next()</code> is called, the function show() is also called. It writes data values in the buffer read by the user. The function <code>next()</code> is called until it returns <code>NULL</code>. The sequence ends when <code>next()</code> returns <code>NULL</code>, then the function <code>stop()</code> is called.</p>
<p>BE CARREFUL: when a sequence is finished, another one starts. That means that at the end of function <code>stop()</code>, the function <code>start()</code> is called again. This loop finishes when the function <code>start()</code> returns <code>NULL</code>. You can see a scheme of this in the figure &ldquo;How seq_file works&rdquo;.</p>
<p>Figure 5-1. How seq_file works</p>
<p><img alt="" src="http://mint-blog.qiniudn.com/seq_file.png" /></p>
<p>Seq_file provides basic functions for file_operations, as seq_read, seq_lseek, and some others. But nothing to write in the <code>/proc</code> file. Of course, you can still use the same way as in the previous example.</p>
<p>Example 5-4. procfs4.c</p>
<pre><code>/**
 *  procfs4.c -  create a &quot;file&quot; in /proc
 *  This program uses the seq_file library to manage the /proc file.
 *
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use proc fs */
#include &lt;linux/seq_file.h&gt; /* for seq_file */

#define PROC_NAME   &quot;iter&quot;

MODULE_AUTHOR(&quot;Philippe Reynes&quot;);
MODULE_LICENSE(&quot;GPL&quot;);

/**
 * This function is called at the beginning of a sequence.
 * ie, when:
 *  - the /proc file is read (first time)
 *  - after the function stop (end of sequence)
 *
 */
static void *my_seq_start(struct seq_file *s, loff_t *pos)
{
    static unsigned long counter = 0;

    /* beginning a new sequence ? */    
    if ( *pos == 0 )
    {   
        /* yes =&gt; return a non null value to begin the sequence */
        return &amp;counter;
    }
    else
    {
        /* no =&gt; it's the end of the sequence, return end to stop reading */
        *pos = 0;
        return NULL;
    }
}

/**
 * This function is called after the beginning of a sequence.
 * It's called untill the return is NULL (this ends the sequence).
 *
 */
static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos)
{
    unsigned long *tmp_v = (unsigned long *)v;
    (*tmp_v)++;
    (*pos)++;
    return NULL;
}

/**
 * This function is called at the end of a sequence
 * 
 */
static void my_seq_stop(struct seq_file *s, void *v)
{
    /* nothing to do, we use a static value in start() */
}

/**
 * This function is called for each &quot;step&quot; of a sequence
 *
 */
static int my_seq_show(struct seq_file *s, void *v)
{
    loff_t *spos = (loff_t *) v;

    seq_printf(s, &quot;%Ld\n&quot;, *spos);
    return 0;
}

/**
 * This structure gather &quot;function&quot; to manage the sequence
 *
 */
static struct seq_operations my_seq_ops = {
    .start = my_seq_start,
    .next  = my_seq_next,
    .stop  = my_seq_stop,
    .show  = my_seq_show
};

/**
 * This function is called when the /proc file is open.
 *
 */
static int my_open(struct inode *inode, struct file *file)
{
    return seq_open(file, &amp;my_seq_ops);
};

/**
 * This structure gather &quot;function&quot; that manage the /proc file
 *
 */
static struct file_operations my_file_ops = {
    .owner   = THIS_MODULE,
    .open    = my_open,
    .read    = seq_read,
    .llseek  = seq_lseek,
    .release = seq_release
};


/**
 * This function is called when the module is loaded
 *
 */
int init_module(void)
{
    struct proc_dir_entry *entry;

    entry = create_proc_entry(PROC_NAME, 0, NULL);
    if (entry) {
        entry-&gt;proc_fops = &amp;my_file_ops;
    }

    return 0;
}

/**
 * This function is called when the module is unloaded.
 *
 */
void cleanup_module(void)
{
    remove_proc_entry(PROC_NAME, NULL);
}
</code></pre>

<p>If you want more information, you can read this web page:</p>
<ul>
<li><a href="http://lwn.net/Articles/22355/">http://lwn.net/Articles/22355/</a></li>
<li><a href="http://www.kernelnewbies.org/documents/seq_file_howto.txt">http://www.kernelnewbies.org/documents/seq_file_howto.txt</a></li>
</ul>
<p>You can also read the code of <code>fs/seq_file.c</code> in the linux kernel.</p>
<h2 id="chapter-6-using-proc-for-input"><a name="user-content-chapter-6-using-proc-for-input" href="#chapter-6-using-proc-for-input" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 6. Using /proc For Input</h2>
<h3 id="61-todo-write-a-chapter-about-sysfs"><a name="user-content-61-todo-write-a-chapter-about-sysfs" href="#61-todo-write-a-chapter-about-sysfs" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>6.1. TODO: Write a chapter about sysfs</h3>
<p>This is just a placeholder for now. Finally I&rsquo;d like to see a (yet to be written) chapter about sysfs instead here. If you are familiar with sysfs and would like to take part in writing this chapter, feel free to contact us (the LKMPG maintainers) for further details.</p>
<h2 id="chapter-7-talking-to-device-files"><a name="user-content-chapter-7-talking-to-device-files" href="#chapter-7-talking-to-device-files" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 7. Talking To Device Files</h2>
<h3 id="71-talking-to-device-files-writes-and-ioctls"><a name="user-content-71-talking-to-device-files-writes-and-ioctls" href="#71-talking-to-device-files-writes-and-ioctls" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>7.1. Talking to Device Files (writes and IOCTLs)</h3>
<p>Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device_write.</p>
<p>This is not always enough. Imagine you had a serial port connected to a modem (even if you have an internal modem, it is still implemented from the CPU&rsquo;s perspective as a serial port connected to a modem, so you don&rsquo;t have to tax your imagination too hard). The natural thing to do would be to use the device file to write things to the modem (either modem commands or data to be sent through the phone line) and read things from the modem (either responses for commands or the data received through the phone line). However, this leaves open the question of what to do when you need to talk to the serial port itself, for example to send the rate at which data is sent and received.</p>
<p>The answer in Unix is to use a special function called ioctl (short for Input Output ConTroL). Every device can have its own ioctl commands, which can be read ioctl&rsquo;s (to send information from a process to the kernel), write ioctl&rsquo;s (to return information to a process),<sup id="fnref:7-1-1"><a class="footnote-ref" href="#fn:7-1-1" rel="footnote">10</a></sup> both or neither. The ioctl function is called with three parameters: the file descriptor of the appropriate device file, the ioctl number, and a parameter, which is of type long so you can use a cast to use it to pass anything.<sup id="fnref:7-1-2"><a class="footnote-ref" href="#fn:7-1-2" rel="footnote">11</a></sup></p>
<p>The ioctl number encodes the major device number, the type of the ioctl, the command, and the type of the parameter. This ioctl number is usually created by a macro call (_IO, _IOR, _IOW or _IOWR &mdash; depending on the type) in a header file. This header file should then be included both by the programs which will use ioctl (so they can generate the appropriate ioctl&rsquo;s) and by the kernel module (so it can understand it). In the example below, the header file is <code>chardev.h</code> and the program which uses it is <code>ioctl.c</code>.</p>
<p>If you want to use ioctls in your own kernel modules, it is best to receive an official ioctl assignment, so if you accidentally get somebody else&rsquo;s ioctls, or if they get yours, you&rsquo;ll know something is wrong. For more information, consult the kernel source tree at <code>Documentation/ioctl-number.txt</code>.</p>
<p>Example 7-1. chardev.c</p>
<pre><code>/*
 *  chardev.c - Create an input/output character device
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/fs.h&gt;
#include &lt;asm/uaccess.h&gt;    /* for get_user and put_user */

#include &quot;chardev.h&quot;
#define SUCCESS 0
#define DEVICE_NAME &quot;char_dev&quot;
#define BUF_LEN 80

/* 
 * Is the device open right now? Used to prevent
 * concurent access into the same device 
 */
static int Device_Open = 0;

/* 
 * The message the device will give when asked 
 */
static char Message[BUF_LEN];

/* 
 * How far did the process reading the message get?
 * Useful if the message is larger than the size of the
 * buffer we get to fill in device_read. 
 */
static char *Message_Ptr;

/* 
 * This is called whenever a process attempts to open the device file 
 */
static int device_open(struct inode *inode, struct file *file)
{
#ifdef DEBUG
    printk(KERN_INFO &quot;device_open(%p)\n&quot;, file);
#endif

    /* 
     * We don't want to talk to two processes at the same time 
     */
    if (Device_Open)
        return -EBUSY;

    Device_Open++;
    /*
     * Initialize the message 
     */
    Message_Ptr = Message;
    try_module_get(THIS_MODULE);
    return SUCCESS;
}

static int device_release(struct inode *inode, struct file *file)
{
#ifdef DEBUG
    printk(KERN_INFO &quot;device_release(%p,%p)\n&quot;, inode, file);
#endif

    /* 
     * We're now ready for our next caller 
     */
    Device_Open--;

    module_put(THIS_MODULE);
    return SUCCESS;
}

/* 
 * This function is called whenever a process which has already opened the
 * device file attempts to read from it.
 */
static ssize_t device_read(struct file *file,   /* see include/linux/fs.h   */
               char __user * buffer,    /* buffer to be
                             * filled with data */
               size_t length,   /* length of the buffer     */
               loff_t * offset)
{
    /* 
     * Number of bytes actually written to the buffer 
     */
    int bytes_read = 0;

#ifdef DEBUG
    printk(KERN_INFO &quot;device_read(%p,%p,%d)\n&quot;, file, buffer, length);
#endif

    /* 
     * If we're at the end of the message, return 0
     * (which signifies end of file) 
     */
    if (*Message_Ptr == 0)
        return 0;

    /* 
     * Actually put the data into the buffer 
     */
    while (length &amp;&amp; *Message_Ptr) {

        /* 
         * Because the buffer is in the user data segment,
         * not the kernel data segment, assignment wouldn't
         * work. Instead, we have to use put_user which
         * copies data from the kernel data segment to the
         * user data segment. 
         */
        put_user(*(Message_Ptr++), buffer++);
        length--;
        bytes_read++;
    }

#ifdef DEBUG
    printk(KERN_INFO &quot;Read %d bytes, %d left\n&quot;, bytes_read, length);
#endif

    /* 
     * Read functions are supposed to return the number
     * of bytes actually inserted into the buffer 
     */
    return bytes_read;
}

/* 
 * This function is called when somebody tries to
 * write into our device file. 
 */
static ssize_t
device_write(struct file *file,
         const char __user * buffer, size_t length, loff_t * offset)
{
    int i;

#ifdef DEBUG
    printk(KERN_INFO &quot;device_write(%p,%s,%d)&quot;, file, buffer, length);
#endif

    for (i = 0; i &lt; length &amp;&amp; i &lt; BUF_LEN; i++)
        get_user(Message[i], buffer + i);

    Message_Ptr = Message;

    /* 
     * Again, return the number of input characters used 
     */
    return i;
}

/* 
 * This function is called whenever a process tries to do an ioctl on our
 * device file. We get two extra parameters (additional to the inode and file
 * structures, which all device functions get): the number of the ioctl called
 * and the parameter given to the ioctl function.
 *
 * If the ioctl is write or read/write (meaning output is returned to the
 * calling process), the ioctl call returns the output of this function.
 *
 */
int device_ioctl(struct inode *inode,   /* see include/linux/fs.h */
         struct file *file, /* ditto */
         unsigned int ioctl_num,    /* number and param for ioctl */
         unsigned long ioctl_param)
{
    int i;
    char *temp;
    char ch;

    /* 
     * Switch according to the ioctl called 
     */
    switch (ioctl_num) {
    case IOCTL_SET_MSG:
        /* 
         * Receive a pointer to a message (in user space) and set that
         * to be the device's message.  Get the parameter given to 
         * ioctl by the process. 
         */
        temp = (char *)ioctl_param;

        /* 
         * Find the length of the message 
         */
        get_user(ch, temp);
        for (i = 0; ch &amp;&amp; i &lt; BUF_LEN; i++, temp++)
            get_user(ch, temp);

        device_write(file, (char *)ioctl_param, i, 0);
        break;

    case IOCTL_GET_MSG:
        /* 
         * Give the current message to the calling process - 
         * the parameter we got is a pointer, fill it. 
         */
        i = device_read(file, (char *)ioctl_param, 99, 0);

        /* 
         * Put a zero at the end of the buffer, so it will be 
         * properly terminated 
         */
        put_user('\0', (char *)ioctl_param + i);
        break;

    case IOCTL_GET_NTH_BYTE:
        /* 
         * This ioctl is both input (ioctl_param) and 
         * output (the return value of this function) 
         */
        return Message[ioctl_param];
        break;
    }

    return SUCCESS;
}

/* Module Declarations */

/* 
 * This structure will hold the functions to be called
 * when a process does something to the device we
 * created. Since a pointer to this structure is kept in
 * the devices table, it can't be local to
 * init_module. NULL is for unimplemented functions. 
 */
struct file_operations Fops = {
    .read = device_read,
    .write = device_write,
    .ioctl = device_ioctl,
    .open = device_open,
    .release = device_release,  /* a.k.a. close */
};

/* 
 * Initialize the module - Register the character device 
 */
int init_module()
{
    int ret_val;
    /* 
     * Register the character device (atleast try) 
     */
    ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &amp;Fops);

    /* 
     * Negative values signify an error 
     */
    if (ret_val &lt; 0) {
        printk(KERN_ALERT &quot;%s failed with %d\n&quot;,
               &quot;Sorry, registering the character device &quot;, ret_val);
        return ret_val;
    }

    printk(KERN_INFO &quot;%s The major device number is %d.\n&quot;,
           &quot;Registeration is a success&quot;, MAJOR_NUM);
    printk(KERN_INFO &quot;If you want to talk to the device driver,\n&quot;);
    printk(KERN_INFO &quot;you'll have to create a device file. \n&quot;);
    printk(KERN_INFO &quot;We suggest you use:\n&quot;);
    printk(KERN_INFO &quot;mknod %s c %d 0\n&quot;, DEVICE_FILE_NAME, MAJOR_NUM);
    printk(KERN_INFO &quot;The device file name is important, because\n&quot;);
    printk(KERN_INFO &quot;the ioctl program assumes that's the\n&quot;);
    printk(KERN_INFO &quot;file you'll use.\n&quot;);

    return 0;
}

/* 
 * Cleanup - unregister the appropriate file from /proc 
 */
void cleanup_module()
{
    int ret;

    /* 
     * Unregister the device 
     */
    ret = unregister_chrdev(MAJOR_NUM, DEVICE_NAME);

    /* 
     * If there's an error, report it 
     */
    if (ret &lt; 0)
        printk(KERN_ALERT &quot;Error: unregister_chrdev: %d\n&quot;, ret);
}
</code></pre>

<p>Example 7-2. chardev.h</p>
<pre><code>/*
 *  chardev.h - the header file with the ioctl definitions.
 *
 *  The declarations here have to be in a header file, because
 *  they need to be known both to the kernel module
 *  (in chardev.c) and the process calling ioctl (ioctl.c)
 */

#ifndef CHARDEV_H
#define CHARDEV_H

#include &lt;linux/ioctl.h&gt;

/* 
 * The major device number. We can't rely on dynamic 
 * registration any more, because ioctls need to know 
 * it. 
 */
#define MAJOR_NUM 100

/* 
 * Set the message of the device driver 
 */
#define IOCTL_SET_MSG _IOR(MAJOR_NUM, 0, char *)
/*
 * _IOR means that we're creating an ioctl command 
 * number for passing information from a user process
 * to the kernel module. 
 *
 * The first arguments, MAJOR_NUM, is the major device 
 * number we're using.
 *
 * The second argument is the number of the command 
 * (there could be several with different meanings).
 *
 * The third argument is the type we want to get from 
 * the process to the kernel.
 */

/* 
 * Get the message of the device driver 
 */
#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *)
/* 
 * This IOCTL is used for output, to get the message 
 * of the device driver. However, we still need the 
 * buffer to place the message in to be input, 
 * as it is allocated by the process.
 */

/* 
 * Get the n'th byte of the message 
 */
#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int)
/* 
 * The IOCTL is used for both input and output. It 
 * receives from the user a number, n, and returns 
 * Message[n]. 
 */

/* 
 * The name of the device file 
 */
#define DEVICE_FILE_NAME &quot;char_dev&quot;

#endif
</code></pre>

<p>Example 7-3. ioctl.c</p>
<pre><code>/*
 *  ioctl.c - the process to use ioctl's to control the kernel module
 *
 *  Until now we could have used cat for input and output.  But now
 *  we need to do ioctl's, which require writing our own process.
 */

/* 
 * device specifics, such as ioctl numbers and the
 * major device file. 
 */
#include &quot;chardev.h&quot;

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;fcntl.h&gt;      /* open */
#include &lt;unistd.h&gt;     /* exit */
#include &lt;sys/ioctl.h&gt;      /* ioctl */

/* 
 * Functions for the ioctl calls 
 */

ioctl_set_msg(int file_desc, char *message)
{
    int ret_val;

    ret_val = ioctl(file_desc, IOCTL_SET_MSG, message);

    if (ret_val &lt; 0) {
        printf(&quot;ioctl_set_msg failed:%d\n&quot;, ret_val);
        exit(-1);
    }
}

ioctl_get_msg(int file_desc)
{
    int ret_val;
    char message[100];

    /* 
     * Warning - this is dangerous because we don't tell
     * the kernel how far it's allowed to write, so it
     * might overflow the buffer. In a real production
     * program, we would have used two ioctls - one to tell
     * the kernel the buffer length and another to give
     * it the buffer to fill
     */
    ret_val = ioctl(file_desc, IOCTL_GET_MSG, message);

    if (ret_val &lt; 0) {
        printf(&quot;ioctl_get_msg failed:%d\n&quot;, ret_val);
        exit(-1);
    }

    printf(&quot;get_msg message:%s\n&quot;, message);
}

ioctl_get_nth_byte(int file_desc)
{
    int i;
    char c;

    printf(&quot;get_nth_byte message:&quot;);

    i = 0;
    do {
        c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++);

        if (c &lt; 0) {
            printf
                (&quot;ioctl_get_nth_byte failed at the %d'th byte:\n&quot;,
                 i);
            exit(-1);
        }

        putchar(c);
    } while (c != 0);
    putchar('\n');
}

/* 
 * Main - Call the ioctl functions 
 */
main()
{
    int file_desc, ret_val;
    char *msg = &quot;Message passed by ioctl\n&quot;;

    file_desc = open(DEVICE_FILE_NAME, 0);
    if (file_desc &lt; 0) {
        printf(&quot;Can't open device file: %s\n&quot;, DEVICE_FILE_NAME);
        exit(-1);
    }

    ioctl_get_nth_byte(file_desc);
    ioctl_get_msg(file_desc);
    ioctl_set_msg(file_desc, msg);

    close(file_desc);
}
</code></pre>

<h2 id="chapter-8-system-calls"><a name="user-content-chapter-8-system-calls" href="#chapter-8-system-calls" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 8. System Calls</h2>
<h3 id="81-system-calls"><a name="user-content-81-system-calls" href="#81-system-calls" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>8.1. System Calls</h3>
<p>So far, the only thing we&rsquo;ve done was to use well defined kernel mechanisms to register<code>/proc</code> files and device handlers. This is fine if you want to do something the kernel programmers thought you&rsquo;d want, such as write a device driver. But what if you want to do something unusual, to change the behavior of the system in some way? Then, you&rsquo;re mostly on your own.</p>
<p>This is where kernel programming gets dangerous. While writing the example below, I killed the <code>open()</code> system call. This meant I couldn&rsquo;t open any files, I couldn&rsquo;t run any programs, and I couldn&rsquo;t shutdown the computer. I had to pull the power switch. Luckily, no files died. To ensure you won&rsquo;t lose any files either, please run sync right before you do the insmod and the rmmod.</p>
<p>Forget about <code>/proc</code> files, forget about device files. They&rsquo;re just minor details. The real process to kernel communication mechanism, the one used by all processes, is system calls. When a process requests a service from the kernel (such as opening a file, forking to a new process, or requesting more memory), this is the mechanism used. If you want to change the behaviour of the kernel in interesting ways, this is the place to do it. By the way, if you want to see which system calls a program uses, run strace <arguments>.</p>
<p>In general, a process is not supposed to be able to access the kernel. It can&rsquo;t access kernel memory and it can&rsquo;t call kernel functions. The hardware of the CPU enforces this (that&rsquo;s the reason why it&rsquo;s called `protected mode&rsquo;).</p>
<p>System calls are an exception to this general rule. What happens is that the process fills the registers with the appropriate values and then calls a special instruction which jumps to a previously defined location in the kernel (of course, that location is readable by user processes, it is not writable by them). Under Intel CPUs, this is done by means of interrupt 0x80. The hardware knows that once you jump to this location, you are no longer running in restricted user mode, but as the operating system kernel &mdash; and therefore you&rsquo;re allowed to do whatever you want.</p>
<p>The location in the kernel a process can jump to is called <code>system_call</code>. The procedure at that location checks the system call number, which tells the kernel what service the process requested. Then, it looks at the table of system calls (<code>sys_call_table</code>) to see the address of the kernel function to call. Then it calls the function, and after it returns, does a few system checks and then return back to the process (or to a different process, if the process time ran out). If you want to read this code, it&rsquo;s at the source file <code>arch/$&lt;$architecture$&gt;$/kernel/entry.S</code>, after the line ENTRY(<code>system_call</code>).</p>
<p>So, if we want to change the way a certain system call works, what we need to do is to write our own function to implement it (usually by adding a bit of our own code, and then calling the original function) and then change the pointer at <code>sys_call_table</code> to point to our function. Because we might be removed later and we don&rsquo;t want to leave the system in an unstable state, it&rsquo;s important for cleanup_module to restore the table to its original state.</p>
<p>The source code here is an example of such a kernel module. We want to <code>spy</code> on a certain user, and to <code>printk()</code> a message whenever that user opens a file. Towards this end, we replace the system call to open a file with our own function, called <code>our_sys_open</code>. This function checks the uid (user&rsquo;s id) of the current process, and if it&rsquo;s equal to the uid we spy on, it calls <code>printk()</code> to display the name of the file to be opened. Then, either way, it calls the original <code>open()</code> function with the same parameters, to actually open the file.</p>
<p>The init_module function replaces the appropriate location in <code>sys_call_table</code> and keeps the original pointer in a variable. The cleanup_module function uses that variable to restore everything back to normal. This approach is dangerous, because of the possibility of two kernel modules changing the same system call. Imagine we have two kernel modules, A and B. A&rsquo;s open system call will be A_open and B&rsquo;s will be B_open. Now, when A is inserted into the kernel, the system call is replaced with A_open, which will call the original sys_open when it&rsquo;s done. Next, B is inserted into the kernel, which replaces the system call with B_open, which will call what it thinks is the original system call, A_open, when it&rsquo;s done.</p>
<p>Now, if B is removed first, everything will be well&mdash;it will simply restore the system call to A_open, which calls the original. However, if A is removed and then B is removed, the system will crash. A&rsquo;s removal will restore the system call to the original, sys_open, cutting B out of the loop. Then, when B is removed, it will restore the system call to what it thinks is the original, A_open, which is no longer in memory. At first glance, it appears we could solve this particular problem by checking if the system call is equal to our open function and if so not changing it at all (so that B won&rsquo;t change the system call when it&rsquo;s removed), but that will cause an even worse problem. When A is removed, it sees that the system call was changed to B_open so that it is no longer pointing to A_open, so it won&rsquo;t restore it to sys_open before it is removed from memory. Unfortunately, B_open will still try to call A_open which is no longer there, so that even without removing B the system would crash.</p>
<p>Note that all the related problems make syscall stealing unfeasiable for production use. In order to keep people from doing potential harmful things sys_call_table is no longer exported. This means, if you want to do something more than a mere dry run of this example, you will have to patch your current kernel in order to have sys_call_table exported. In the example directory you will find a README and the patch. As you can imagine, such modifications are not to be taken lightly. Do not try this on valueable systems (ie systems that you do not own - or cannot restore easily). You&rsquo;ll need to get the complete sourcecode of this guide as a tarball in order to get the patch and the README. Depending on your kernel version, you might even need to hand apply the patch. Still here? Well, so is this chapter. If Wyle E. Coyote was a kernel hacker, this would be the first thing he&rsquo;d try. ;)</p>
<p>Example 8-1. syscall.c</p>
<pre><code>/*
 *  syscall.c
 *
 *  System call &quot;stealing&quot; sample.
 */

/* 
 * Copyright (C) 2001 by Peter Jay Salzman 
 */

/* 
 * The necessary header files 
 */

/*
 * Standard in kernel modules 
 */
#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module, */
#include &lt;linux/moduleparam.h&gt;  /* which will have params */
#include &lt;linux/unistd.h&gt;   /* The list of system calls */

/* 
 * For the current (process) structure, we need
 * this to know who the current user is. 
 */
#include &lt;linux/sched.h&gt;
#include &lt;asm/uaccess.h&gt;

/* 
 * The system call table (a table of functions). We
 * just define this as external, and the kernel will
 * fill it up for us when we are insmod'ed
 *
 * sys_call_table is no longer exported in 2.6.x kernels.
 * If you really want to try this DANGEROUS module you will
 * have to apply the supplied patch against your current kernel
 * and recompile it.
 */
extern void *sys_call_table[];

/* 
 * UID we want to spy on - will be filled from the
 * command line 
 */
static int uid;
module_param(uid, int, 0644);

/* 
 * A pointer to the original system call. The reason
 * we keep this, rather than call the original function
 * (sys_open), is because somebody else might have
 * replaced the system call before us. Note that this
 * is not 100% safe, because if another module
 * replaced sys_open before us, then when we're inserted
 * we'll call the function in that module - and it
 * might be removed before we are.
 *
 * Another reason for this is that we can't get sys_open.
 * It's a static variable, so it is not exported. 
 */
asmlinkage int (*original_call) (const char *, int, int);

/* 
 * The function we'll replace sys_open (the function
 * called when you call the open system call) with. To
 * find the exact prototype, with the number and type
 * of arguments, we find the original function first
 * (it's at fs/open.c).
 *
 * In theory, this means that we're tied to the
 * current version of the kernel. In practice, the
 * system calls almost never change (it would wreck havoc
 * and require programs to be recompiled, since the system
 * calls are the interface between the kernel and the
 * processes).
 */
asmlinkage int our_sys_open(const char *filename, int flags, int mode)
{
    int i = 0;
    char ch;

    /* 
     * Check if this is the user we're spying on 
     */
    if (uid == current-&gt;uid) {
        /* 
         * Report the file, if relevant 
         */
        printk(&quot;Opened file by %d: &quot;, uid);
        do {
            get_user(ch, filename + i);
            i++;
            printk(&quot;%c&quot;, ch);
        } while (ch != 0);
        printk(&quot;\n&quot;);
    }

    /* 
     * Call the original sys_open - otherwise, we lose
     * the ability to open files 
     */
    return original_call(filename, flags, mode);
}

/* 
 * Initialize the module - replace the system call 
 */
int init_module()
{
    /* 
     * Warning - too late for it now, but maybe for
     * next time... 
     */
    printk(KERN_ALERT &quot;I'm dangerous. I hope you did a &quot;);
    printk(KERN_ALERT &quot;sync before you insmod'ed me.\n&quot;);
    printk(KERN_ALERT &quot;My counterpart, cleanup_module(), is even&quot;);
    printk(KERN_ALERT &quot;more dangerous. If\n&quot;);
    printk(KERN_ALERT &quot;you value your file system, it will &quot;);
    printk(KERN_ALERT &quot;be \&quot;sync; rmmod\&quot; \n&quot;);
    printk(KERN_ALERT &quot;when you remove this module.\n&quot;);

    /* 
     * Keep a pointer to the original function in
     * original_call, and then replace the system call
     * in the system call table with our_sys_open 
     */
    original_call = sys_call_table[__NR_open];
    sys_call_table[__NR_open] = our_sys_open;

    /* 
     * To get the address of the function for system
     * call foo, go to sys_call_table[__NR_foo]. 
     */

    printk(KERN_INFO &quot;Spying on UID:%d\n&quot;, uid);

    return 0;
}

/* 
 * Cleanup - unregister the appropriate file from /proc 
 */
void cleanup_module()
{
    /* 
     * Return the system call back to normal 
     */
    if (sys_call_table[__NR_open] != our_sys_open) {
        printk(KERN_ALERT &quot;Somebody else also played with the &quot;);
        printk(KERN_ALERT &quot;open system call\n&quot;);
        printk(KERN_ALERT &quot;The system may be left in &quot;);
        printk(KERN_ALERT &quot;an unstable state.\n&quot;);
    }

    sys_call_table[__NR_open] = original_call;
}
</code></pre>

<h2 id="chapter-9-blocking-processes"><a name="user-content-chapter-9-blocking-processes" href="#chapter-9-blocking-processes" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 9. Blocking Processes</h2>
<h3 id="91-blocking-processes"><a name="user-content-91-blocking-processes" href="#91-blocking-processes" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>9.1. Blocking Processes</h3>
<p>What do you do when somebody asks you for something you can&rsquo;t do right away? If you&rsquo;re a human being and you&rsquo;re bothered by a human being, the only thing you can say is: &ldquo;Not right now, I&rsquo;m busy. Go away!&rdquo;. But if you&rsquo;re a kernel module and you&rsquo;re bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that&rsquo;s the way multiple processes appear to run on the same time on a single CPU).</p>
<p>This kernel module is an example of this. The file (called <code>/proc/sleep</code>) can only be opened by a single process at a time. If the file is already open, the kernel module calls <code>wait_event_interruptible</code><sup id="fnref:9-1-1"><a class="footnote-ref" href="#fn:9-1-1" rel="footnote">12</a></sup>. This function changes the status of the task (a task is the kernel data structure which holds information about a process and the system call it&rsquo;s in, if any) to <code>TASK_INTERRUPTIBLE</code>, which means that the task will not run until it is woken up somehow, and adds it to WaitQ, the queue of tasks waiting to access the file. Then, the function calls the scheduler to context switch to a different process, one which has some use for the CPU.</p>
<p>When a process is done with the file, it closes it, and module_close is called. That function wakes up all the processes in the queue (there&rsquo;s no mechanism to only wake up one of them). It then returns and the process which just closed the file can continue to run. In time, the scheduler decides that that process has had enough and gives control of the CPU to another process. Eventually, one of the processes which was in the queue will be given control of the CPU by the scheduler. It starts at the point right after the call to <code>module_interruptible_sleep_on</code>[9-1-2]. It can then proceed to set a global variable to tell all the other processes that the file is still open and go on with its life. When the other processes get a piece of the CPU, they&rsquo;ll see that global variable and go back to sleep.</p>
<p>So we&rsquo;ll use tail -f to keep the file open in the background, while trying to access it with another process (again in the background, so that we need not switch to a different vt). As soon as the first background process is killed with <code>kill %1</code> , the second is woken up, is able to access the file and finally terminates.</p>
<p>To make our life more interesting, <code>module_close</code> doesn&rsquo;t have a monopoly on waking up the processes which wait to access the file. A signal, such as Ctrl+c (<code>SIGINT</code>) can also wake up a process<sup id="fnref:9-1-3"><a class="footnote-ref" href="#fn:9-1-3" rel="footnote">14</a></sup>. In that case, we want to return with <code>-EINTR</code> immediately. This is important so users can, for example, kill the process before it receives the file.</p>
<p>There is one more point to remember. Some times processes don&rsquo;t want to sleep, they want either to get what they want immediately, or to be told it cannot be done. Such processes use the <code>O_NONBLOCK</code> flag when opening the file. The kernel is supposed to respond by returning with the error code <code>-EAGAIN</code> from operations which would otherwise block, such as opening the file in this example. The program cat_noblock, available in the source directory for this chapter, can be used to open a file with <code>O_NONBLOCK</code>.</p>
<pre><code>hostname:~/lkmpg-examples/09-BlockingProcesses# insmod sleep.ko
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
Last input:
hostname:~/lkmpg-examples/09-BlockingProcesses# tail -f /proc/sleep &amp;
Last input:
Last input:
Last input:
Last input:
Last input:
Last input:
Last input:
tail: /proc/sleep: file truncated
[1] 6540
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
Open would block
hostname:~/lkmpg-examples/09-BlockingProcesses# kill %1
[1]+  Terminated              tail -f /proc/sleep
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
Last input:
hostname:~/lkmpg-examples/09-BlockingProcesses#
</code></pre>

<p>Example 9-1. sleep.c</p>
<pre><code>/*
 *  sleep.c - create a /proc file, and if several processes try to open it at
 *  the same time, put all but one to sleep
 */

#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use proc fs */
#include &lt;linux/sched.h&gt;    /* For putting processes to sleep and 
                   waking them up */
#include &lt;asm/uaccess.h&gt;    /* for get_user and put_user */

/* 
 * The module's file functions 
 */

/* 
 * Here we keep the last message received, to prove that we can process our
 * input
 */
#define MESSAGE_LENGTH 80
static char Message[MESSAGE_LENGTH];

static struct proc_dir_entry *Our_Proc_File;
#define PROC_ENTRY_FILENAME &quot;sleep&quot;

/* 
 * Since we use the file operations struct, we can't use the special proc
 * output provisions - we have to use a standard read function, which is this
 * function
 */
static ssize_t module_output(struct file *file, /* see include/linux/fs.h   */
                 char *buf, /* The buffer to put data to 
                       (in the user segment)    */
                 size_t len,    /* The length of the buffer */
                 loff_t * offset)
{
    static int finished = 0;
    int i;
    char message[MESSAGE_LENGTH + 30];

    /* 
     * Return 0 to signify end of file - that we have nothing 
     * more to say at this point.
     */
    if (finished) {
        finished = 0;
        return 0;
    }

    /* 
     * If you don't understand this by now, you're hopeless as a kernel
     * programmer.
     */
    sprintf(message, &quot;Last input:%s\n&quot;, Message);
    for (i = 0; i &lt; len &amp;&amp; message[i]; i++)
        put_user(message[i], buf + i);

    finished = 1;
    return i;       /* Return the number of bytes &quot;read&quot; */
}

/* 
 * This function receives input from the user when the user writes to the /proc
 * file.
 */
static ssize_t module_input(struct file *file,  /* The file itself */
                const char *buf,    /* The buffer with input */
                size_t length,  /* The buffer's length */
                loff_t * offset)
{               /* offset to file - ignore */
    int i;

    /* 
     * Put the input into Message, where module_output will later be 
     * able to use it
     */
    for (i = 0; i &lt; MESSAGE_LENGTH - 1 &amp;&amp; i &lt; length; i++)
        get_user(Message[i], buf + i);
    /* 
     * we want a standard, zero terminated string 
     */
    Message[i] = '\0';

    /* 
     * We need to return the number of input characters used 
     */
    return i;
}

/* 
 * 1 if the file is currently open by somebody 
 */
int Already_Open = 0;

/* 
 * Queue of processes who want our file 
 */
DECLARE_WAIT_QUEUE_HEAD(WaitQ);
/* 
 * Called when the /proc file is opened 
 */
static int module_open(struct inode *inode, struct file *file)
{
    /* 
     * If the file's flags include O_NONBLOCK, it means the process doesn't
     * want to wait for the file.  In this case, if the file is already 
     * open, we should fail with -EAGAIN, meaning &quot;you'll have to try 
     * again&quot;, instead of blocking a process which would rather stay awake.
     */
    if ((file-&gt;f_flags &amp; O_NONBLOCK) &amp;&amp; Already_Open)
        return -EAGAIN;

    /* 
     * This is the correct place for try_module_get(THIS_MODULE) because 
     * if a process is in the loop, which is within the kernel module,
     * the kernel module must not be removed.
     */
    try_module_get(THIS_MODULE);

    /* 
     * If the file is already open, wait until it isn't 
     */

    while (Already_Open) {
        int i, is_sig = 0;

        /* 
         * This function puts the current process, including any system
         * calls, such as us, to sleep.  Execution will be resumed right
         * after the function call, either because somebody called 
         * wake_up(&amp;WaitQ) (only module_close does that, when the file 
         * is closed) or when a signal, such as Ctrl-C, is sent 
         * to the process
         */
        wait_event_interruptible(WaitQ, !Already_Open);

        /* 
         * If we woke up because we got a signal we're not blocking, 
         * return -EINTR (fail the system call).  This allows processes
         * to be killed or stopped.
         */

/*
 * Emmanuel Papirakis:
 *
 * This is a little update to work with 2.2.*.  Signals now are contained in
 * two words (64 bits) and are stored in a structure that contains an array of
 * two unsigned longs.  We now have to make 2 checks in our if.
 *
 * Ori Pomerantz:
 *
 * Nobody promised me they'll never use more than 64 bits, or that this book
 * won't be used for a version of Linux with a word size of 16 bits.  This code
 * would work in any case.
 */
        for (i = 0; i &lt; _NSIG_WORDS &amp;&amp; !is_sig; i++)
            is_sig =
                current-&gt;pending.signal.sig[i] &amp; ~current-&gt;
                blocked.sig[i];

        if (is_sig) {
            /* 
             * It's important to put module_put(THIS_MODULE) here,
             * because for processes where the open is interrupted
             * there will never be a corresponding close. If we 
             * don't decrement the usage count here, we will be 
             * left with a positive usage count which we'll have no
             * way to bring down to zero, giving us an immortal 
             * module, which can only be killed by rebooting 
             * the machine.
             */
            module_put(THIS_MODULE);
            return -EINTR;
        }
    }

    /* 
     * If we got here, Already_Open must be zero 
     */

    /* 
     * Open the file 
     */
    Already_Open = 1;
    return 0;       /* Allow the access */
}

/* 
 * Called when the /proc file is closed 
 */
int module_close(struct inode *inode, struct file *file)
{
    /* 
     * Set Already_Open to zero, so one of the processes in the WaitQ will
     * be able to set Already_Open back to one and to open the file. All 
     * the other processes will be called when Already_Open is back to one,
     * so they'll go back to sleep.
     */
    Already_Open = 0;

    /* 
     * Wake up all the processes in WaitQ, so if anybody is waiting for the
     * file, they can have it.
     */
    wake_up(&amp;WaitQ);

    module_put(THIS_MODULE);

    return 0;       /* success */
}

/*
 * This function decides whether to allow an operation (return zero) or not
 * allow it (return a non-zero which indicates why it is not allowed).
 *
 * The operation can be one of the following values:
 * 0 - Execute (run the &quot;file&quot; - meaningless in our case)
 * 2 - Write (input to the kernel module)
 * 4 - Read (output from the kernel module)
 *
 * This is the real function that checks file permissions. The permissions
 * returned by ls -l are for reference only, and can be overridden here.
 */
static int module_permission(struct inode *inode, int op, struct nameidata *nd)
{
    /* 
     * We allow everybody to read from our module, but only root (uid 0)
     * may write to it
     */
    if (op == 4 || (op == 2 &amp;&amp; current-&gt;euid == 0))
        return 0;

    /* 
     * If it's anything else, access is denied 
     */
    return -EACCES;
}

/* 
 * Structures to register as the /proc file, with pointers to all the relevant
 * functions.
 */

/* 
 * File operations for our proc file. This is where we place pointers to all
 * the functions called when somebody tries to do something to our file. NULL
 * means we don't want to deal with something.
 */
static struct file_operations File_Ops_4_Our_Proc_File = {
    .read = module_output,  /* &quot;read&quot; from the file */
    .write = module_input,  /* &quot;write&quot; to the file */
    .open = module_open,    /* called when the /proc file is opened */
    .release = module_close,    /* called when it's closed */
};

/* 
 * Inode operations for our proc file.  We need it so we'll have somewhere to
 * specify the file operations structure we want to use, and the function we
 * use for permissions. It's also possible to specify functions to be called
 * for anything else which could be done to an inode (although we don't bother,
 * we just put NULL).
 */

static struct inode_operations Inode_Ops_4_Our_Proc_File = {
    .permission = module_permission,    /* check for permissions */
};

/* 
 * Module initialization and cleanup 
 */

/* 
 * Initialize the module - register the proc file 
 */

int init_module()
{

    Our_Proc_File = create_proc_entry(PROC_ENTRY_FILENAME, 0644, NULL);

    if (Our_Proc_File == NULL) {
        remove_proc_entry(PROC_ENTRY_FILENAME, &amp;proc_root);
        printk(KERN_ALERT &quot;Error: Could not initialize /proc/test\n&quot;);
        return -ENOMEM;
    }

    Our_Proc_File-&gt;owner = THIS_MODULE;
    Our_Proc_File-&gt;proc_iops = &amp;Inode_Ops_4_Our_Proc_File;
    Our_Proc_File-&gt;proc_fops = &amp;File_Ops_4_Our_Proc_File;
    Our_Proc_File-&gt;mode = S_IFREG | S_IRUGO | S_IWUSR;
    Our_Proc_File-&gt;uid = 0;
    Our_Proc_File-&gt;gid = 0;
    Our_Proc_File-&gt;size = 80;

    printk(KERN_INFO &quot;/proc/test created\n&quot;);

    return 0;
}

/* 
 * Cleanup - unregister our file from /proc.  This could get dangerous if
 * there are still processes waiting in WaitQ, because they are inside our
 * open function, which will get unloaded. I'll explain how to avoid removal
 * of a kernel module in such a case in chapter 10.
 */
void cleanup_module()
{
    remove_proc_entry(PROC_ENTRY_FILENAME, &amp;proc_root);

    printk(KERN_INFO &quot;/proc/test removed\n&quot;);
}
</code></pre>

<p>Example 9-2. cat_noblock.c</p>
<pre><code>/* cat_noblock.c - open a file and display its contents, but exit rather than
 * wait for input */


/* Copyright (C) 1998 by Ori Pomerantz */



#include &lt;stdio.h&gt;    /* standard I/O */
#include &lt;fcntl.h&gt;    /* for open */
#include &lt;unistd.h&gt;   /* for read */ 
#include &lt;stdlib.h&gt;   /* for exit */
#include &lt;errno.h&gt;    /* for errno */

#define MAX_BYTES 1024*4


main(int argc, char *argv[])
{
  int    fd;  /* The file descriptor for the file to read */
  size_t bytes; /* The number of bytes read */
  char   buffer[MAX_BYTES]; /* The buffer for the bytes */  


  /* Usage */
  if (argc != 2) {
    printf(&quot;Usage: %s &lt;filename&gt;\n&quot;, argv[0]);
    puts(&quot;Reads the content of a file, but doesn't wait for input&quot;);
    exit(-1);
  }

  /* Open the file for reading in non blocking mode */ 
  fd = open(argv[1], O_RDONLY | O_NONBLOCK);

  /* If open failed */
  if (fd == -1) {
    if (errno = EAGAIN)
      puts(&quot;Open would block&quot;);
    else
      puts(&quot;Open failed&quot;);
    exit(-1);
  }

  /* Read the file and output its contents */
  do {
    int i;

    /* Read characters from the file */
    bytes = read(fd, buffer, MAX_BYTES);

    /* If there's an error, report it and die */
    if (bytes == -1) {
      if (errno = EAGAIN)
    puts(&quot;Normally I'd block, but you told me not to&quot;);
      else
    puts(&quot;Another read error&quot;);
      exit(-1);
    }

    /* Print the characters */
    if (bytes &gt; 0) {
      for(i=0; i&lt;bytes; i++)
    putchar(buffer[i]);
    }

    /* While there are no errors and the file isn't over */
  } while (bytes &gt; 0);
}
</code></pre>

<h2 id="chapter-10-replacing-printks"><a name="user-content-chapter-10-replacing-printks" href="#chapter-10-replacing-printks" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 10. Replacing Printks</h2>
<h3 id="101-replacing-printk"><a name="user-content-101-replacing-printk" href="#101-replacing-printk" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>10.1. Replacing printk</h3>
<p>In <a href="#Section 1.2.1.2">Section 1.2.1.2</a>, I said that X and kernel module programming don&rsquo;t mix. That&rsquo;s true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty<sup id="fnref:10-1-1"><a class="footnote-ref" href="#fn:10-1-1" rel="footnote">15</a></sup> the command to load the module came from.</p>
<p>The way this is done is by using <code>current</code>, a pointer to the currently running task, to get the current task&rsquo;s structure. Then, we look inside that structure to find a pointer to a string write function, which we use to write a string to the tty.</p>
<p>Example 10-1. print_string.c</p>
<pre><code>/* 
 *  print_string.c - Send output to the tty we're running on, regardless if it's
 *  through X11, telnet, etc.  We do this by printing the string to the tty
 *  associated with the current task.
 */
#include &lt;linux/kernel.h&gt;
#include &lt;linux/module.h&gt;
#include &lt;linux/init.h&gt;
#include &lt;linux/sched.h&gt;    /* For current */
#include &lt;linux/tty.h&gt;      /* For the tty declarations */
#include &lt;linux/version.h&gt;  /* For LINUX_VERSION_CODE */

MODULE_LICENSE(&quot;GPL&quot;);
MODULE_AUTHOR(&quot;Peter Jay Salzman&quot;);

static void print_string(char *str)
{
    struct tty_struct *my_tty;

    /* 
     * tty struct went into signal struct in 2.6.6 
     */
#if ( LINUX_VERSION_CODE &lt;= KERNEL_VERSION(2,6,5) )
    /* 
     * The tty for the current task 
     */
    my_tty = current-&gt;tty;
#else
    /* 
     * The tty for the current task, for 2.6.6+ kernels 
     */
    my_tty = current-&gt;signal-&gt;tty;
#endif

    /* 
     * If my_tty is NULL, the current task has no tty you can print to 
     * (ie, if it's a daemon).  If so, there's nothing we can do.
     */
    if (my_tty != NULL) {

        /* 
         * my_tty-&gt;driver is a struct which holds the tty's functions,
         * one of which (write) is used to write strings to the tty. 
         * It can be used to take a string either from the user's or 
         * kernel's memory segment.
         *
         * The function's 1st parameter is the tty to write to,
         * because the same function would normally be used for all 
         * tty's of a certain type.  The 2nd parameter controls 
         * whether the function receives a string from kernel
         * memory (false, 0) or from user memory (true, non zero). 
         * BTW: this param has been removed in Kernels &gt; 2.6.9
         * The (2nd) 3rd parameter is a pointer to a string.
         * The (3rd) 4th parameter is the length of the string.
         *
         * As you will see below, sometimes it's necessary to use
         * preprocessor stuff to create code that works for different
         * kernel versions. The (naive) approach we've taken here 
         * does not scale well. The right way to deal with this 
         * is described in section 2 of 
         * linux/Documentation/SubmittingPatches
         */
        ((my_tty-&gt;driver)-&gt;write) (my_tty,  /* The tty itself */
#if ( LINUX_VERSION_CODE &lt;= KERNEL_VERSION(2,6,9) )     
                       0,   /* Don't take the string 
                           from user space        */
#endif
                       str, /* String                 */
                       strlen(str));    /* Length */

        /* 
         * ttys were originally hardware devices, which (usually) 
         * strictly followed the ASCII standard.  In ASCII, to move to
         * a new line you need two characters, a carriage return and a
         * line feed.  On Unix, the ASCII line feed is used for both 
         * purposes - so we can't just use \n, because it wouldn't have
         * a carriage return and the next line will start at the
         * column right after the line feed.
         *
         * This is why text files are different between Unix and 
         * MS Windows.  In CP/M and derivatives, like MS-DOS and 
         * MS Windows, the ASCII standard was strictly adhered to,
         * and therefore a newline requirs both a LF and a CR.
         */

#if ( LINUX_VERSION_CODE &lt;= KERNEL_VERSION(2,6,9) )     
        ((my_tty-&gt;driver)-&gt;write) (my_tty, 0, &quot;\015\012&quot;, 2);
#else
        ((my_tty-&gt;driver)-&gt;write) (my_tty, &quot;\015\012&quot;, 2);
#endif
    }
}

static int __init print_string_init(void)
{
    print_string(&quot;The module has been inserted.  Hello world!&quot;);
    return 0;
}

static void __exit print_string_exit(void)
{
    print_string(&quot;The module has been removed.  Farewell world!&quot;);
}

module_init(print_string_init);
module_exit(print_string_exit);
</code></pre>

<h3 id="102-flashing-keyboard-leds"><a name="user-content-102-flashing-keyboard-leds" href="#102-flashing-keyboard-leds" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>10.2. Flashing keyboard LEDs</h3>
<p>In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.</p>
<p>The following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded.</p>
<p>Example 10-2. kbleds.c</p>
<pre><code>/* 
 *  kbleds.c - Blink keyboard leds until the module is unloaded.
 */

#include &lt;linux/module.h&gt;
#include &lt;linux/config.h&gt;
#include &lt;linux/init.h&gt;
#include &lt;linux/tty.h&gt;      /* For fg_console, MAX_NR_CONSOLES */
#include &lt;linux/kd.h&gt;       /* For KDSETLED */
#include &lt;linux/vt.h&gt;
#include &lt;linux/console_struct.h&gt;   /* For vc_cons */

MODULE_DESCRIPTION(&quot;Example module illustrating the use of Keyboard LEDs.&quot;);
MODULE_AUTHOR(&quot;Daniele Paolo Scarpazza&quot;);
MODULE_LICENSE(&quot;GPL&quot;);

struct timer_list my_timer;
struct tty_driver *my_driver;
char kbledstatus = 0;

#define BLINK_DELAY   HZ/5
#define ALL_LEDS_ON   0x07
#define RESTORE_LEDS  0xFF

/*
 * Function my_timer_func blinks the keyboard LEDs periodically by invoking
 * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual 
 * terminal ioctl operations, please see file:
 *     /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl().
 *
 * The argument to KDSETLED is alternatively set to 7 (thus causing the led 
 * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF
 * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus
 * the LEDs reflect the actual keyboard status).  To learn more on this, 
 * please see file:
 *     /usr/src/linux/drivers/char/keyboard.c, function setledstate().
 * 
 */

static void my_timer_func(unsigned long ptr)
{
    int *pstatus = (int *)ptr;

    if (*pstatus == ALL_LEDS_ON)
        *pstatus = RESTORE_LEDS;
    else
        *pstatus = ALL_LEDS_ON;

    (my_driver-&gt;ioctl) (vc_cons[fg_console].d-&gt;vc_tty, NULL, KDSETLED,
                *pstatus);

    my_timer.expires = jiffies + BLINK_DELAY;
    add_timer(&amp;my_timer);
}

static int __init kbleds_init(void)
{
    int i;

    printk(KERN_INFO &quot;kbleds: loading\n&quot;);
    printk(KERN_INFO &quot;kbleds: fgconsole is %x\n&quot;, fg_console);
    for (i = 0; i &lt; MAX_NR_CONSOLES; i++) {
        if (!vc_cons[i].d)
            break;
        printk(KERN_INFO &quot;poet_atkm: console[%i/%i] #%i, tty %lx\n&quot;, i,
               MAX_NR_CONSOLES, vc_cons[i].d-&gt;vc_num,
               (unsigned long)vc_cons[i].d-&gt;vc_tty);
    }
    printk(KERN_INFO &quot;kbleds: finished scanning consoles\n&quot;);

    my_driver = vc_cons[fg_console].d-&gt;vc_tty-&gt;driver;
    printk(KERN_INFO &quot;kbleds: tty driver magic %x\n&quot;, my_driver-&gt;magic);

    /*
     * Set up the LED blink timer the first time
     */
    init_timer(&amp;my_timer);
    my_timer.function = my_timer_func;
    my_timer.data = (unsigned long)&amp;kbledstatus;
    my_timer.expires = jiffies + BLINK_DELAY;
    add_timer(&amp;my_timer);

    return 0;
}

static void __exit kbleds_cleanup(void)
{
    printk(KERN_INFO &quot;kbleds: unloading...\n&quot;);
    del_timer(&amp;my_timer);
    (my_driver-&gt;ioctl) (vc_cons[fg_console].d-&gt;vc_tty, NULL, KDSETLED,
                RESTORE_LEDS);
}

module_init(kbleds_init);
module_exit(kbleds_cleanup);
</code></pre>

<p>If none of the examples in this chapter fit your debugging needs there might yet be some other tricks to try. Ever wondered what CONFIG_LL_DEBUG in make menuconfig is good for? If you activate that you get low level access to the serial port. While this might not sound very powerful by itself, you can patch <code>kernel/printk.c</code> or any other essential syscall to use printascii, thus makeing it possible to trace virtually everything what your code does over a serial line. If you find yourself porting the kernel to some new and former unsupported architecture this is usually amongst the first things that should be implemented. Logging over a netconsole might also be worth a try.</p>
<p>While you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive. Adding debug code can change the situation enough to make the bug seem to dissappear. Thus you should try to keep debug code to a minimum and make sure it does not show up in production code.</p>
<h2 id="chapter-11-scheduling-tasks"><a name="user-content-chapter-11-scheduling-tasks" href="#chapter-11-scheduling-tasks" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 11. Scheduling Tasks</h2>
<h3 id="111-scheduling-tasks"><a name="user-content-111-scheduling-tasks" href="#111-scheduling-tasks" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>11.1. Scheduling Tasks</h3>
<p>Very often, we have &ldquo;housekeeping&rdquo; tasks which have to be done at a certain time, or every so often. If the task is to be done by a process, we do it by putting it in the <code>crontab</code> file. If the task is to be done by a kernel module, we have two possibilities. The first is to put a process in the <code>crontab</code> file which will wake up the module by a system call when necessary, for example by opening a file. This is terribly inefficient, however &ndash; we run a new process off of <code>crontab</code>, read a new executable to memory, and all this just to wake up a kernel module which is in memory anyway.</p>
<p>Instead of doing that, we can create a function that will be called once for every timer interrupt. The way we do this is we create a task, held in a <code>workqueue_struct</code> structure, which will hold a pointer to the function. Then, we use queue_delayed_work to put that task on a task list called my_workqueue, which is the list of tasks to be executed on the next timer interrupt. Because we want the function to keep on being executed, we need to put it back on my_workqueue whenever it is called, for the next timer interrupt.</p>
<p>There&rsquo;s one more point we need to remember here. When a module is removed by rmmod, first its reference count is checked. If it is zero, <code>module_cleanup</code> is called. Then, the module is removed from memory with all its functions. Things need to be shut down properly, or bad things will happen. See the code below how this can be done in a safe way.</p>
<p>Example 11-1. sched.c</p>
<pre><code>/*
 *  sched.c - scheduale a function to be called on every timer interrupt.
 *
 *  Copyright (C) 2001 by Peter Jay Salzman
 */

/* 
 * The necessary header files 
 */

/* 
 * Standard in kernel modules 
 */
#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/proc_fs.h&gt;  /* Necessary because we use the proc fs */
#include &lt;linux/workqueue.h&gt;    /* We scheduale tasks here */
#include &lt;linux/sched.h&gt;    /* We need to put ourselves to sleep 
                   and wake up later */
#include &lt;linux/init.h&gt;     /* For __init and __exit */
#include &lt;linux/interrupt.h&gt;    /* For irqreturn_t */

struct proc_dir_entry *Our_Proc_File;
#define PROC_ENTRY_FILENAME &quot;sched&quot;
#define MY_WORK_QUEUE_NAME &quot;WQsched.c&quot;

/* 
 * The number of times the timer interrupt has been called so far 
 */
static int TimerIntrpt = 0;

static void intrpt_routine(void *);

static int die = 0;     /* set this to 1 for shutdown */

/* 
 * The work queue structure for this task, from workqueue.h 
 */
static struct workqueue_struct *my_workqueue;

static struct work_struct Task;
static DECLARE_WORK(Task, intrpt_routine, NULL);

/* 
 * This function will be called on every timer interrupt. Notice the void*
 * pointer - task functions can be used for more than one purpose, each time
 * getting a different parameter.
 */
static void intrpt_routine(void *irrelevant)
{
    /* 
     * Increment the counter 
     */
    TimerIntrpt++;

    /* 
     * If cleanup wants us to die
     */
    if (die == 0)
        queue_delayed_work(my_workqueue, &amp;Task, 100);
}

/* 
 * Put data into the proc fs file. 
 */
ssize_t
procfile_read(char *buffer,
          char **buffer_location,
          off_t offset, int buffer_length, int *eof, void *data)
{
    int len;        /* The number of bytes actually used */

    /* 
     * It's static so it will still be in memory 
     * when we leave this function
     */
    static char my_buffer[80];

    /* 
     * We give all of our information in one go, so if anybody asks us
     * if we have more information the answer should always be no.
     */
    if (offset &gt; 0)
        return 0;

    /* 
     * Fill the buffer and get its length 
     */
    len = sprintf(my_buffer, &quot;Timer called %d times so far\n&quot;, TimerIntrpt);

    /* 
     * Tell the function which called us where the buffer is 
     */
    *buffer_location = my_buffer;

    /* 
     * Return the length 
     */
    return len;
}

/* 
 * Initialize the module - register the proc file 
 */
int __init init_module()
{
    /*
     * Create our /proc file
     */
    Our_Proc_File = create_proc_entry(PROC_ENTRY_FILENAME, 0644, NULL);

    if (Our_Proc_File == NULL) {
        remove_proc_entry(PROC_ENTRY_FILENAME, &amp;proc_root);
        printk(KERN_ALERT &quot;Error: Could not initialize /proc/%s\n&quot;,
               PROC_ENTRY_FILENAME);
        return -ENOMEM;
    }

    Our_Proc_File-&gt;read_proc = procfile_read;
    Our_Proc_File-&gt;owner = THIS_MODULE;
    Our_Proc_File-&gt;mode = S_IFREG | S_IRUGO;
    Our_Proc_File-&gt;uid = 0;
    Our_Proc_File-&gt;gid = 0;
    Our_Proc_File-&gt;size = 80;

    /* 
     * Put the task in the work_timer task queue, so it will be executed at
     * next timer interrupt
     */
    my_workqueue = create_workqueue(MY_WORK_QUEUE_NAME);
    queue_delayed_work(my_workqueue, &amp;Task, 100);


    printk(KERN_INFO &quot;/proc/%s created\n&quot;, PROC_ENTRY_FILENAME);

    return 0;
}

/* 
 * Cleanup
 */
void __exit cleanup_module()
{
    /* 
     * Unregister our /proc file 
     */
    remove_proc_entry(PROC_ENTRY_FILENAME, &amp;proc_root);
    printk(KERN_INFO &quot;/proc/%s removed\n&quot;, PROC_ENTRY_FILENAME);

    die = 1;        /* keep intrp_routine from queueing itself */
    cancel_delayed_work(&amp;Task); /* no &quot;new ones&quot; */
    flush_workqueue(my_workqueue);  /* wait till all &quot;old ones&quot; finished */
    destroy_workqueue(my_workqueue);

    /* 
     * Sleep until intrpt_routine is called one last time. This is 
     * necessary, because otherwise we'll deallocate the memory holding 
     * intrpt_routine and Task while work_timer still references them.
     * Notice that here we don't allow signals to interrupt us.
     *
     * Since WaitQ is now not NULL, this automatically tells the interrupt
     * routine it's time to die.
     */

}

/* 
 * some work_queue related functions
 * are just available to GPL licensed Modules 
 */
MODULE_LICENSE(&quot;GPL&quot;);
</code></pre>

<p><span id = "chapter 12">  </span> </p>
<h2 id="chapter-12-interrupt-handlers"><a name="user-content-chapter-12-interrupt-handlers" href="#chapter-12-interrupt-handlers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 12. Interrupt Handlers</h2>
<h3 id="121-interrupt-handlers"><a name="user-content-121-interrupt-handlers" href="#121-interrupt-handlers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>12.1. Interrupt Handlers</h3>
<h4 id="1211-interrupt-handlers"><a name="user-content-1211-interrupt-handlers" href="#1211-interrupt-handlers" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>12.1.1. Interrupt Handlers</h4>
<p>Except for the last chapter, everything we did in the kernel so far we&rsquo;ve done as a response to a process asking for it, either by dealing with a special file, sending an <code>ioctl()</code>, or issuing a system call. But the job of the kernel isn&rsquo;t just to respond to process requests. Another job, which is every bit as important, is to speak to the hardware connected to the machine.</p>
<p>There are two types of interaction between the CPU and the rest of the computer&rsquo;s hardware. The first type is when the CPU gives orders to the hardware, the other is when the hardware needs to tell the CPU something. The second, called interrupts, is much harder to implement because it has to be dealt with when convenient for the hardware, not the CPU. Hardware devices typically have a very small amount of RAM, and if you don&rsquo;t read their information when available, it is lost.</p>
<p>Under Linux, hardware interrupts are called IRQ&rsquo;s (InterruptRe quests)[^12-1-1]. There are two types of IRQ&rsquo;s, short and long. A short IRQ is one which is expected to take a very short period of time, during which the rest of the machine will be blocked and no other interrupts will be handled. A long IRQ is one which can take longer, and during which other interrupts may occur (but not interrupts from the same device). If at all possible, it&rsquo;s better to declare an interrupt handler to be long.</p>
<p>When the CPU receives an interrupt, it stops whatever it&rsquo;s doing (unless it&rsquo;s processing a more important interrupt, in which case it will deal with this one only when the more important one is done), saves certain parameters on the stack and calls the interrupt handler. This means that certain things are not allowed in the interrupt handler itself, because the system is in an unknown state. The solution to this problem is for the interrupt handler to do what needs to be done immediately, usually read something from the hardware or send something to the hardware, and then schedule the handling of the new information at a later time (this is called the &ldquo;bottom half&rdquo;) and return. The kernel is then   guaranteed to call the bottom half as soon as possible &ndash; and when it does, everything allowed in kernel modules will be allowed.</p>
<p>The way to implement this is to call request_irq() to get your interrupt handler called when the relevant IRQ is received.[^12-1-2] This function receives the IRQ number, the name of the function, flags, a name for <code>/proc/interrupts</code> and a parameter to pass to the interrupt handler. Usually there is a certain number of IRQs available. How many IRQs there are is hardware-dependent. The flags can include <code>SA_SHIRQ</code> to indicate you&rsquo;re willing to share the IRQ with other interrupt handlers (usually because a number of hardware devices sit on the same IRQ) and <code>SA_INTERRUPT</code> to indicate this is a fast interrupt. This function will only succeed if there isn&rsquo;t already a handler on this IRQ, or if you&rsquo;re both willing to share.</p>
<p>Then, from within the interrupt handler, we communicate with the hardware and then use <code>queue_work()</code> mark_bh(<code>BH_IMMEDIATE</code>) to schedule the bottom half.</p>
<h4 id="1212-keyboards-on-the-intel-architecture"><a name="user-content-1212-keyboards-on-the-intel-architecture" href="#1212-keyboards-on-the-intel-architecture" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>12.1.2. Keyboards on the Intel Architecture</h4>
<p>The rest of this chapter is completely Intel specific. If you&rsquo;re not running on an Intel platform, it will not work. Don&rsquo;t even try to compile the code here.</p>
<p>I had a problem with writing the sample code for this chapter. On one hand, for an example to be useful it has to run on everybody&rsquo;s computer with meaningful results. On the other hand, the kernel already includes device drivers for all of the common devices, and those device drivers won&rsquo;t coexist with what I&rsquo;m going to write. The solution I&rsquo;ve found was to write something for the keyboard interrupt, and disable the regular keyboard interrupt handler first. Since it is defined as a static symbol in the kernel source files (specifically, <code>drivers/char/keyboard.c</code>), there is no way to restore it. Before insmod&rsquo;ing this code, do on another terminal sleep 120; reboot if you value your file system.</p>
<p>This code binds itself to IRQ 1, which is the IRQ of the keyboard controlled under Intel architectures. Then, when it receives a keyboard interrupt, it reads the keyboard&rsquo;s status (that&rsquo;s the purpose of the inb(0x64)) and the scan code, which is the value returned by the keyboard. Then, as soon as the kernel thinks it&rsquo;s feasible, it runs got_char which gives the code of the key used (the first seven bits of the scan code) and whether it has been pressed (if the 8th bit is zero) or released (if it&rsquo;s one).</p>
<p>Example 12-1. intrpt.c</p>
<pre><code>/*
 *  intrpt.c - An interrupt handler.
 *
 *  Copyright (C) 2001 by Peter Jay Salzman
 */

/* 
 * The necessary header files 
 */

/* 
 * Standard in kernel modules 
 */
#include &lt;linux/kernel.h&gt;   /* We're doing kernel work */
#include &lt;linux/module.h&gt;   /* Specifically, a module */
#include &lt;linux/sched.h&gt;
#include &lt;linux/workqueue.h&gt;
#include &lt;linux/interrupt.h&gt;    /* We want an interrupt */
#include &lt;asm/io.h&gt;

#define MY_WORK_QUEUE_NAME &quot;WQsched.c&quot;

static struct workqueue_struct *my_workqueue;

/* 
 * This will get called by the kernel as soon as it's safe
 * to do everything normally allowed by kernel modules.
 */
static void got_char(void *scancode)
{
    printk(KERN_INFO &quot;Scan Code %x %s.\n&quot;,
           (int)*((char *)scancode) &amp; 0x7F,
           *((char *)scancode) &amp; 0x80 ? &quot;Released&quot; : &quot;Pressed&quot;);
}

/* 
 * This function services keyboard interrupts. It reads the relevant
 * information from the keyboard and then puts the non time critical
 * part into the work queue. This will be run when the kernel considers it safe.
 */
irqreturn_t irq_handler(int irq, void *dev_id, struct pt_regs *regs)
{
    /* 
     * This variables are static because they need to be
     * accessible (through pointers) to the bottom half routine.
     */
    static int initialised = 0;
    static unsigned char scancode;
    static struct work_struct task;
    unsigned char status;

    /* 
     * Read keyboard status
     */
    status = inb(0x64);
    scancode = inb(0x60);

    if (initialised == 0) {
        INIT_WORK(&amp;task, got_char, &amp;scancode);
        initialised = 1;
    } else {
        PREPARE_WORK(&amp;task, got_char, &amp;scancode);
    }

    queue_work(my_workqueue, &amp;task);

    return IRQ_HANDLED;
}

/* 
 * Initialize the module - register the IRQ handler 
 */
int init_module()
{
    my_workqueue = create_workqueue(MY_WORK_QUEUE_NAME);

    /* 
     * Since the keyboard handler won't co-exist with another handler,
     * such as us, we have to disable it (free its IRQ) before we do
     * anything.  Since we don't know where it is, there's no way to
     * reinstate it later - so the computer will have to be rebooted
     * when we're done.
     */
    free_irq(1, NULL);

    /* 
     * Request IRQ 1, the keyboard IRQ, to go to our irq_handler.
     * SA_SHIRQ means we're willing to have othe handlers on this IRQ.
     * SA_INTERRUPT can be used to make the handler into a fast interrupt.
     */
    return request_irq(1,   /* The number of the keyboard IRQ on PCs */
               irq_handler, /* our handler */
               SA_SHIRQ, &quot;test_keyboard_irq_handler&quot;,
               (void *)(irq_handler));
}

/* 
 * Cleanup 
 */
void cleanup_module()
{
    /* 
     * This is only here for completeness. It's totally irrelevant, since
     * we don't have a way to restore the normal keyboard interrupt so the
     * computer is completely useless and has to be rebooted.
     */
    free_irq(1, NULL);
}

/* 
 * some work_queue related functions are just available to GPL licensed Modules
 */
MODULE_LICENSE(&quot;GPL&quot;);
</code></pre>

<p>[12-1-1]: This is standard nomencalture on the Intel architecture where Linux originated.<br />
[12-1-2]: In practice IRQ handling can be a bit more complex. Hardware is often designed in a way that chains two interrupt controllers, so that all the IRQs from interrupt controller B are cascaded to a certain IRQ from interrupt controller A. Of course that requires that the kernel finds out which IRQ it really was afterwards and that adds overhead. Other architectures offer some special, very low overhead, so called &ldquo;fast IRQ&rdquo; or FIQs. To take advantage of them requires handlers to be written in assembler, so they do not really fit into the kernel. They can be made to work similar to the others, but after that procedure, they&rsquo;re no longer any faster than &ldquo;common&rdquo; IRQs. SMP enabled kernels running on systems with more than one processor need to solve another truckload of problems. It&rsquo;s not enough to know if a certain IRQs has happend, it&rsquo;s also important for what CPU(s) it was for. People still interested in more details, might want to do a web search for &ldquo;APIC&rdquo; now ;)</p>
<h2 id="chapter-13-symmetric-multi-processing"><a name="user-content-chapter-13-symmetric-multi-processing" href="#chapter-13-symmetric-multi-processing" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 13. Symmetric Multi Processing</h2>
<h3 id="131-symmetrical-multi-processing"><a name="user-content-131-symmetrical-multi-processing" href="#131-symmetrical-multi-processing" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>13.1. Symmetrical Multi-Processing</h3>
<p>One of the easiest and cheapest ways to improve hardware performance is to put more than one CPU on the board. This can be done either making the different CPU&rsquo;s take on different jobs (asymmetrical multi-processing) or by making them all run in parallel, doing the same job (symmetrical multi-processing, a.k.a. SMP). Doing asymmetrical multi-processing effectively requires specialized knowledge about the tasks the computer should do, which is unavailable in a general purpose operating system such as Linux. On the other hand, symmetrical multi-processing is relatively easy to implement.</p>
<p>By relatively easy, I mean exactly that: not that it&rsquo;s really easy. In a symmetrical multi-processing environment, the CPU&rsquo;s share the same memory, and as a result code running in one CPU can affect the memory used by another. You can no longer be certain that a variable you&rsquo;ve set to a certain value in the previous line still has that value; the other CPU might have played with it while you weren&rsquo;t looking. Obviously, it&rsquo;s impossible to program like this.</p>
<p>In the case of process programming this normally isn&rsquo;t an issue, because a process will normally only run on one CPU at a time<sup id="fnref:13-1-1"><a class="footnote-ref" href="#fn:13-1-1" rel="footnote">16</a></sup>. The kernel, on the other hand, could be called by different processes running on different CPU&rsquo;s.</p>
<p>In version 2.0.x, this isn&rsquo;t a problem because the entire kernel is in one big spinlock. This means that if one CPU is in the kernel and another CPU wants to get in, for example because of a system call, it has to wait until the first CPU is done. This makes Linux SMP safe<sup id="fnref:13-1-2"><a class="footnote-ref" href="#fn:13-1-2" rel="footnote">17</a></sup>, but inefficient.</p>
<p>In version 2.2.x, several CPU&rsquo;s can be in the kernel at the same time. This is something module writers need to be aware of.</p>
<h2 id="chapter-14-common-pitfalls"><a name="user-content-chapter-14-common-pitfalls" href="#chapter-14-common-pitfalls" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>Chapter 14. Common Pitfalls</h2>
<h3 id="141-common-pitfalls"><a name="user-content-141-common-pitfalls" href="#141-common-pitfalls" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>14.1. Common Pitfalls</h3>
<p>Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.</p>
<ul>
<li>Using standard libraries : You can&rsquo;t do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms.</li>
<li>Disabling interrupts : You might need to do this for a short time and that is OK, but if you don&rsquo;t enable them afterwards, your system will be stuck and you&rsquo;ll have to power it off.</li>
<li>Sticking your head inside a large carnivore : I probably don&rsquo;t have to warn you about this, but I figured I will anyway, just in case.</li>
</ul>
<h2 id="a-changes-20-to-22"><a name="user-content-a-changes-20-to-22" href="#a-changes-20-to-22" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>A. Changes: 2.0 To 2.2</h2>
<h3 id="a11-changes-between-24-and-26"><a name="user-content-a11-changes-between-24-and-26" href="#a11-changes-between-24-and-26" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>A.1.1. Changes between 2.4 and 2.6</h3>
<p>I don&rsquo;t know the entire kernel well enough to document all of the changes. Some hints for porting can be found by comparing this version of the LKMPG with it&rsquo;s counterpart for kernel 2.4. Apart from that, anybody who needs to port drivers from 2.4 to 2.6 kernels might want to visit <a href="http://lwn.net/Articles/driver-porting/">http://lwn.net/Articles/driver-porting/</a> . If you still can&rsquo;t find an example that exactly meets your needs there, find a driver that&rsquo;s similar to your driver and present in both kernel versions. File comparison tools like xxdiff or meld can be a great help then. Also check if your driver is covered by docs in <code>linux/Documentation/</code>. Before starting with porting and in case you&rsquo;re stuck it&rsquo;s a good idea to find an appropiate mailinglist and ask people there for pointers.</p>
<h2 id="b-where-to-go-from-here"><a name="user-content-b-where-to-go-from-here" href="#b-where-to-go-from-here" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>B. Where To Go From Here</h2>
<h3 id="b1-where-from-here"><a name="user-content-b1-where-from-here" href="#b1-where-from-here" class="headeranchor-link" aria-hidden="true"><span class="headeranchor"></span></a>B.1. Where From Here?</h3>
<p>I could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there&rsquo;s a need for that &ndash; you&rsquo;d have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven&rsquo;t touched upon, such as bootstrapping or the disk interface.</p>
<p>However, I chose not to. My purpose in writing this book was to provide initiation into the mysteries of kernel module programming and to teach the common techniques for that purpose. For people seriously interested in kernel programming, I recommend Juan-Mariano de Goyeneche&rsquo;s <a href="http://jungla.dit.upm.es/~jmseyas/linux/kernel/hackers-docs.html">list of kernel resources</a> . Also, as Linus said, the best way to learn the kernel is to read the source code yourself.</p>
<p>If you&rsquo;re interested in more examples of short kernel modules, I recommend Phrack magazine. Even if you&rsquo;re not interested in security, and as a programmer you should be, the kernel modules there are good examples of what you can do inside the kernel, and they&rsquo;re short enough not to require too much effort to understand.</p>
<p>I hope I have helped you in your quest to become a better programmer, or at least to have fun through technology. And, if you do write useful kernel modules, I hope you publish them under the GPL, so I can use them too.</p>
<p>If you&rsquo;d like to contribute to this guide, please contact one the maintainers for details. As you&rsquo;ve already seen, there&rsquo;s a placeholder chapter now, waiting to be filled with examples for sysfs.</p>
<h2 id="doc-index"><a href="http://www.tldp.org/LDP/lkmpg/2.6/html/doc-index.html">Doc Index</a></h2>
<div class="footnote">
<hr />
<ol>
<li id="fn:1">
<p>In earlier versions of linux, this was known as kerneld.&#160;<a class="footnote-backref" href="#fnref:1" rev="footnote" title="Jump back to footnote 1 in the text">&#8617;</a></p>
</li>
<li id="fn:2">
<p>If such a file exists. Note that the acual behavoir might be distribution-dependent.    If you&rsquo;re interested in the details,read the man pages that came with module-init-tools, and see for yourself what&rsquo;s really going on. You could use something like strace modprobe dummy to find out how dummy.ko gets loaded. FYI: The dummy.ko I&rsquo;m talking about here is part of the mainline kernel and can be found in the networking section. It needs to be compiled as a module (and installed, of course) for this to work.&#160;<a class="footnote-backref" href="#fnref:2" rev="footnote" title="Jump back to footnote 2 in the text">&#8617;</a></p>
</li>
<li id="fn:3">
<p>If you are modifying the kernel, to avoid overwriting your existing modules you may want to use the EXTRAVERSION variable in the kernel Makefile to create a seperate directory.&#160;<a class="footnote-backref" href="#fnref:3" rev="footnote" title="Jump back to footnote 3 in the text">&#8617;</a></p>
</li>
<li id="fn:3-1-1">
<p>It&rsquo;s an invaluable tool for figuring out things like what files a program is trying to access. Ever have a program bail silently because it couldn&rsquo;t find a file? It&rsquo;s a PITA!&#160;<a class="footnote-backref" href="#fnref:3-1-1" rev="footnote" title="Jump back to footnote 4 in the text">&#8617;</a></p>
</li>
<li id="fn:3-1-2">
<p>I&rsquo;m a physicist, not a computer scientist, Jim!&#160;<a class="footnote-backref" href="#fnref:3-1-2" rev="footnote" title="Jump back to footnote 5 in the text">&#8617;</a></p>
</li>
<li id="fn:3-1-3">
<p>This isn&rsquo;t quite the same thing as `building all your modules into the kernel&rsquo;, although the idea is the same.&#160;<a class="footnote-backref" href="#fnref:3-1-3" rev="footnote" title="Jump back to footnote 6 in the text">&#8617;</a></p>
</li>
<li id="fn:4-1-1">
<p>This is by convention. When writing a driver, it&rsquo;s OK to put the device file in your current directory. Just make sure you place it in <code>/dev</code> for a production driver&#160;<a class="footnote-backref" href="#fnref:4-1-1" rev="footnote" title="Jump back to footnote 7 in the text">&#8617;</a></p>
</li>
<li id="fn:5-1-1">
<p>In version 2.0, in version 2.2 this is done automatically if we set the inode to zero.&#160;<a class="footnote-backref" href="#fnref:5-1-1" rev="footnote" title="Jump back to footnote 8 in the text">&#8617;</a></p>
</li>
<li id="fn:5-3-1">
<p>The difference between the two is that file operations deal with the file itself, and inode operations deal with ways of referencing the file, such as creating links to it.&#160;<a class="footnote-backref" href="#fnref:5-3-1" rev="footnote" title="Jump back to footnote 9 in the text">&#8617;</a></p>
</li>
<li id="fn:7-1-1">
<p>Notice that here the roles of read and write are reversed again, so in ioctl&rsquo;s read is to send information to the kernel and write is to receive information from the kernel.&#160;<a class="footnote-backref" href="#fnref:7-1-1" rev="footnote" title="Jump back to footnote 10 in the text">&#8617;</a></p>
</li>
<li id="fn:7-1-2">
<p>This isn&rsquo;t exact. You won&rsquo;t be able to pass a structure, for example, through an ioctl &mdash; but you will be able to pass a pointer to the structure.&#160;<a class="footnote-backref" href="#fnref:7-1-2" rev="footnote" title="Jump back to footnote 11 in the text">&#8617;</a></p>
</li>
<li id="fn:9-1-1">
<p>The easiest way to keep a file open is to open it with tail -f.&#160;<a class="footnote-backref" href="#fnref:9-1-1" rev="footnote" title="Jump back to footnote 12 in the text">&#8617;</a></p>
</li>
<li id="fn:9-1-2">
<p>This means that the process is still in kernel mode &ndash; as far as the process is concerned, it issued the open system call and the system call hasn&rsquo;t returned yet. The process doesn&rsquo;t know somebody else used the CPU for most of the time between the moment it issued the call and the moment it returned.&#160;<a class="footnote-backref" href="#fnref:9-1-2" rev="footnote" title="Jump back to footnote 13 in the text">&#8617;</a></p>
</li>
<li id="fn:9-1-3">
<p>This is because we used <code>module_interruptible_sleep_on</code>. We could have used <code>module_sleep_on</code> instead, but that would have resulted is extremely angry users whose Ctrl+cs are ignored.&#160;<a class="footnote-backref" href="#fnref:9-1-3" rev="footnote" title="Jump back to footnote 14 in the text">&#8617;</a></p>
</li>
<li id="fn:10-1-1">
<p>Teletype, originally a combination keyboard-printer used to communicate with a Unix system, and today an abstraction for the text stream used for a Unix program, whether it&rsquo;s a physical terminal, an xterm on an X display, a network connection used with telnet, etc.&#160;<a class="footnote-backref" href="#fnref:10-1-1" rev="footnote" title="Jump back to footnote 15 in the text">&#8617;</a></p>
</li>
<li id="fn:13-1-1">
<p>The exception is threaded processes, which can run on several CPU&rsquo;s at once.&#160;<a class="footnote-backref" href="#fnref:13-1-1" rev="footnote" title="Jump back to footnote 16 in the text">&#8617;</a></p>
</li>
<li id="fn:13-1-2">
<p>Meaning it is safe to use it with SMP&#160;<a class="footnote-backref" href="#fnref:13-1-2" rev="footnote" title="Jump back to footnote 17 in the text">&#8617;</a></p>
</li>
</ol>
</div></article></body></html>